<?php
/**
 * @version $Id: admin.unocart.php 25 2010-05-21 22:52:30Z vladzimirs@gmail.com $
 * @package UnoCart
 * @copyright Авторские права (C) 2009-2010 UnoCart team & (C) 2007-2010 Joostina team &. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * UnoCart! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл help/copyright.php.
 */
//   For 1.5
// 1.5
global $unocartConfig, $ordering_category, $payment_type, $shop_type, $format_currency;
// 1/5
defined('_VALID_MOS') or die('Restricted access');
// GET config
require_once (JPATH_BASE .
    "/administrator/components/com_unocart/unocart.class.php");
require_once (JPATH_BASE . "/components/com_unocart/functions.php");
require_once (JPATH_BASE .
    "/administrator/components/com_unocart/specialtype.php");
$unocartConfig = loadConfig();
$_REQUEST = recursiveHtmlSpecialChars($_REQUEST);
$_GET = recursiveHtmlSpecialChars($_GET);
$_POST = recursiveHtmlSpecialChars($_POST);
$database = &unocartFactory::getDBO();
$unocartConfig->cur_lang = Jconfig::getInstance()->config_lang;
if (file_exists(JPATH_BASE . '/administrator/components/com_unocart/lang/admin_' .
    $unocartConfig->mainLanguage . '.php')) {
    require_once (JPATH_BASE . '/administrator/components/com_unocart/lang/admin_' .
        $unocartConfig->mainLanguage . '.php');
} else {
    require_once (JPATH_BASE .
        '/administrator/components/com_unocart/lang/admin_english.php');
}
$act = mosGetParam($_REQUEST, 'act', 'panel');
$task = mosGetParam($_REQUEST, 'task');
$parentid = mosGetParam($_REQUEST, 'parentid', '');
if ($task == 'panel')
    header("Location: index2.php?option=com_unocart&act=config");
// When xmlhttprequest, to admin_html pidklyuchju piznishe
if ($act == 'ajax') {
    switch ($task) {
        case 'showCategory':
            echo getAllCategoriesLevel(mosGetParam($_REQUEST, 'catid'));
            break;
        case 'preview_pdf':
            previewPdf();
            break;
        case 'checkDirectory':
            echo isWritable(mosGetParam($_REQUEST, 'directory'));
            break;
    }
    return;
}
// When frontend dann no include admin_html
if ($act != 'ajax_f')
    require_once (JPATH_BASE .
        "/administrator/components/com_unocart/admin.unocart.html.php");
// Get the current language
switch ($act) {
    case 'report':
        switch ($task) {
            case 'send':
                sendReport();
                break;
            default:
                HTML_UNOCART::showFormReport();
        }
        break;
    case 'info':
        HTML_UNOCART::showInfo();
        break;
    case 'config':
        switch ($task) {
            case 'save':
                saveConfig();
                break;
            case 'updateMenu':
                updateMenuTexts();
                mosRedirect('index2.php?option=com_unocart&act=config');
                break;
            case 'cancel':
                mosRedirect('index2.php?option=com_unocart&act=config');
                break;
            default:
                showConfig();
        }
        break;
    case 'panel':
        HTML_UNOCART::showPanel();
        break;
    case 'categories':
        switch ($task) {
            case 'edit':
                editCategory($cat_id = (isset($_POST['cid'])) ? ($_POST['cid'][0]) : (mosGetParam
                    ($_REQUEST, 'catid')));
                break;
            case 'new':
                editCategory(null, $parentid);
                break;
            case 'save':
                saveCategory(0);
                break;
            case 'apply':
                saveCategory(1);
                break;
            case 'cancel':
                showTreeCategory(getParentCategory(mosGetParam($_REQUEST, 'catid')));
                break;
            case 'remove':
                deleteCategory(mosGetParam($_REQUEST, 'cid'));
                break;
            case 'order':
                orderCategory(mosGetParam($_REQUEST, 'order'), mosGetParam($_REQUEST, 'id'),
                    mosGetParam($_REQUEST, 'number'));
                break;
            case 'publish':
                publishCategory(mosGetParam($_REQUEST, 'cid'), 1);
                break;
            case 'unpublish':
                publishCategory(mosGetParam($_REQUEST, 'cid'), 0);
                break;
            default:
                showTreeCategory(mosGetParam($_REQUEST, 'catid', 0));
        }
        break;
    case 'currencies':
        switch ($task) {
            case 'new':
                editCurrency();
                break;
            case 'edit':
                editCurrency(mosGetParam($_REQUEST, 'currency_id'));
                break;
            case 'publish':
                publishCurrency(mosGetParam($_REQUEST, 'cid'), 1);
                break;
            case 'unpublish':
                publishCurrency(mosGetParam($_REQUEST, 'cid'), 0);
                break;
            case 'save':
                saveCurrency(mosGetParam($_REQUEST, 'currency_id', 0), 0);
                break;
            case 'apply':
                saveCurrency(mosGetParam($_REQUEST, 'currency_id', 0), 1);
                break;
            case 'remove':
                deleteCurrency(mosGetParam($_REQUEST, 'cid'));
                break;
            case 'order':
                orderCurrency(mosGetParam($_REQUEST, 'order'), mosGetParam($_REQUEST, 'id'),
                    mosGetParam($_REQUEST, 'number'));
                break;
            case 'cancel':
                showCurrencies();
                break;
            default:
                showCurrencies();
                break;
        }
        break;

    case 'countries':
        switch ($task) {
            case 'new':
                editCountry();
                break;
            case 'edit':
                editCountry(mosGetParam($_REQUEST, 'country_id'));
                break;
            case 'publish':
                publishCountry(mosGetParam($_REQUEST, 'cid'), 1);
                break;
            case 'unpublish':
                publishCountry(mosGetParam($_REQUEST, 'cid'), 0);
                break;
            case 'save':
                saveCountry(mosGetParam($_REQUEST, 'country_id', 0), 0);
                break;
            case 'apply':
                saveCountry(mosGetParam($_REQUEST, 'country_id', 0), 1);
                break;
            case 'remove':
                deleteCountry(mosGetParam($_REQUEST, 'cid'));
                break;
            case 'order':
                orderCountry(mosGetParam($_REQUEST, 'order'), mosGetParam($_REQUEST, 'id'),
                    mosGetParam($_REQUEST, 'number'));
                break;
            case 'cancel':
                showCountries();
                break;
            default:
                showCountries();
                break;
        }
        break;


    case 'coupons':
        switch ($task) {
            case 'new':
                editCoupon();
                break;
            case 'edit':
                editCoupon(mosGetParam($_REQUEST, 'coupon_id'));
                break;
            case 'publish':
                publishCoupon(mosGetParam($_REQUEST, 'cid'), 1);
                break;
            case 'unpublish':
                publishCoupon(mosGetParam($_REQUEST, 'cid'), 0);
                break;
            case 'save':
                saveCoupon(mosGetParam($_REQUEST, 'coupon_id', 0), 0);
                break;
            case 'apply':
                saveCoupon(mosGetParam($_REQUEST, 'coupon_id', 0), 1);
                break;
            case 'remove':
                deleteCoupon(mosGetParam($_REQUEST, 'cid'));
                break;
            case 'cancel':
                showCoupons();
                break;
            default:
                showCoupons();
                break;
        }
        break;
    case 'taxes':
        switch ($task) {
            case 'new':
                editTax();
                break;
            case 'edit':
                editTax(mosGetParam($_REQUEST, 'tax_id'));
                break;
            case 'save':
                saveTax(mosGetParam($_REQUEST, 'tax_id', 0), 0);
                break;
            case 'apply':
                saveTax(mosGetParam($_REQUEST, 'tax_id', 0), 1);
                break;
            case 'remove':
                deleteTax(mosGetParam($_REQUEST, 'cid'));
                break;
            case 'cancel':
                showTaxes();
                break;
            default:
                showTaxes();
                break;
        }
        break;
    case 'manufacturers':
        switch ($task) {
            case 'new':
                editManufacturer();
                break;
            case 'edit':
                editManufacturer(mosGetParam($_REQUEST, 'man_id'));
                break;
            case 'save':
                saveManufacturer(mosGetParam($_REQUEST, 'man_id', 0), 0);
                break;
            case 'apply':
                saveManufacturer(mosGetParam($_REQUEST, 'man_id', 0), 1);
                break;
            case 'remove':
                deleteManufacturer(mosGetParam($_REQUEST, 'cid'));
                break;
            case 'cancel':
                showManufacturers();
                break;
            case 'publish':
                publishManufacturer(mosGetParam($_REQUEST, 'cid'), 1);
                break;
            case 'unpublish':
                publishManufacturer(mosGetParam($_REQUEST, 'cid'), 0);
                break;
            default:
                showManufacturers();
                break;
        }
        break;
    case 'users':
        switch ($task) {
            case 'show':
                showShopUsers();
                break;
            case 'edit':
                editShopUser(mosGetParam($_REQUEST, 'user_id'));
                break;
            case 'remove':
                removeShopUser(mosGetParam($_REQUEST, 'cid'));
                break;
            case 'save':
                saveShopUser(mosGetParam($_REQUEST, 'user_id'));
                break;
            default:
                showShopUsers();
        }
        break;

    case 'usergroups':
        switch ($task) {
            case 'new':
                editUsergroup(0);
                break;
            case 'edit':
                editUsergroup(mosGetParam($_REQUEST, 'usergroup_id'));
                break;
            case 'save':
                saveUsergroup(mosGetParam($_REQUEST, 'usergroup_id'), 0);
                break;
            case 'apply':
                saveUsergroup(mosGetParam($_REQUEST, 'usergroup_id'), 1);
                break;
            case 'remove':
                deleteUsergroup(mosGetParam($_REQUEST, 'cid'));
                break;
            default:
                showUsergroups();
        }
        break;

    case 'products':
        switch ($task) {
            case 'new':
                editProduct(0);
                break;
            case 'edit':
                editProduct($prod_id = (isset($_POST['cid'])) ? ($_POST['cid'][0]) : (mosGetParam
                    ($_REQUEST, 'product_id')));
                break;
            case 'save':
                saveProduct(0);
                break;
            case 'apply':
                saveProduct(1);
                break;
            case 'cancel':
                showProducts(mosGetParam($_REQUEST, 'current_cat'), 0);
                break;
            case 'remove':
                deleteProduct(mosGetParam($_REQUEST, 'cid'));
                showProducts(mosGetParam($_REQUEST, 'current_cat', 0));
                break;
            case 'order':
                orderProduct(mosGetParam($_REQUEST, 'order'), mosGetParam($_REQUEST,
                    'product_id'), mosGetParam($_REQUEST, 'number'), mosGetParam($_REQUEST,
                    'category_id'));
                showProducts(mosGetParam($_REQUEST, 'category_id', 0));
                break;
            case 'publish':
                publishProduct(mosGetParam($_REQUEST, 'cid'), 1);
                showProducts(mosGetParam($_REQUEST, 'current_cat', 0));
                break;
            case 'unpublish':
                publishProduct(mosGetParam($_REQUEST, 'cid'), 0);
                showProducts(mosGetParam($_REQUEST, 'current_cat', 0));
                break;
            case 'copy':
                copyProduct(mosGetParam($_REQUEST, 'cid'));
                showProducts(mosGetParam($_REQUEST, 'current_cat', 0));
                break;
            default:
                showProducts(mosGetParam($_REQUEST, 'current_cat', 0));
        }
        break;
    case 'payments':
        switch ($task) {
            case 'new':
                editPaymentMethod();
                break;
            case 'edit':
                editPaymentMethod(mosGetParam($_REQUEST, 'payment_id'));
                break;
            case 'publish':
                publishPaymentMethod(mosGetParam($_REQUEST, 'cid'), 1);
                break;
            case 'unpublish':
                publishPaymentMethod(mosGetParam($_REQUEST, 'cid'), 0);
                break;
            case 'order':
                orderPaymentMethod(mosGetParam($_REQUEST, 'order'), mosGetParam($_REQUEST, 'id'),
                    mosGetParam($_REQUEST, 'number'));
                break;
            case 'save':
                savePaymentMethod(mosGetParam($_REQUEST, 'payment_id', 0), 0);
                break;
            case 'apply':
                savePaymentMethod(mosGetParam($_REQUEST, 'payment_id', 0), 1);
                break;
            case 'remove':
                deletePaymentMethod(mosGetParam($_REQUEST, 'cid'));
                break;
            case 'cancel':
                showPaymentMethods();
                break;
            default:
                showPaymentMethods();
                break;
        }
        break;
    case 'shippings':
        switch ($task) {
            case 'new':
                editShippingMethod();
                break;
            case 'edit':
                editShippingMethod(mosGetParam($_REQUEST, 'shipping_id'));
                break;
            case 'publish':
                publishShippingMethod(mosGetParam($_REQUEST, 'cid'), 1);
                break;
            case 'unpublish':
                publishShippingMethod(mosGetParam($_REQUEST, 'cid'), 0);
                break;
            case 'order':
                orderShippingMethod(mosGetParam($_REQUEST, 'order'), mosGetParam($_REQUEST, 'id'),
                    mosGetParam($_REQUEST, 'number'));
                break;
            case 'save':
                saveShippingMethod(mosGetParam($_REQUEST, 'shipping_id', 0), 0);
                break;
            case 'apply':
                saveShippingMethod(mosGetParam($_REQUEST, 'shipping_id', 0), 1);
                break;
            case 'remove':
                deleteShippingMethod(mosGetParam($_REQUEST, 'cid'));
                break;
            case 'cancel':
                showShippingMethods();
                break;
            default:
                showShippingMethods();
                break;
        }
        break;

    case 'shippings_prices':
        switch ($task) {
            case 'new':
                editShippingMethodPrice(0);
                break;
            case 'edit':
                editShippingMethodPrice(mosGetParam($_REQUEST, 'sh_pr_method_id'));
                break;
            case 'save':
                saveShippingMethodPrice(mosGetParam($_REQUEST, 'sh_pr_method_id', 0), 0);
                break;
            case 'apply':
                saveShippingMethodPrice(mosGetParam($_REQUEST, 'sh_pr_method_id', 0), 1);
                break;
            case 'remove':
                deleteShippingMethodPrice(mosGetParam($_REQUEST, 'cid'));
                break;
            case 'cancel':
                showShippingMethodsPrices();
                break;
            default:
                showShippingMethodsPrices();
                break;
        }
        break;

    case 'orders':
        switch ($task) {
            case 'show':
                showOrders();
                break;
            case 'print':
                printOrder(mosGetParam($_REQUEST, 'order_id'));
                break;
            case 'show_one':
                showOrder(mosGetParam($_REQUEST, 'order_id'));
                break;
            case 'update_one_status':
                updateStatus(mosGetParam($_REQUEST, 'order_id'), mosGetParam($_REQUEST,
                    'order_status'), mosGetParam($_REQUEST, 'status_id'), mosGetParam($_REQUEST,
                    'notify', 0), mosGetParam($_REQUEST, 'comments', ''), mosGetParam($_REQUEST,
                    'include', ''), 1);
                break;
            case 'update_status':
                updateStatus(mosGetParam($_REQUEST, 'order_id'), mosGetParam($_REQUEST,
                    'order_status'), mosGetParam($_REQUEST, 'status_id'), mosGetParam($_REQUEST,
                    'notify', 0), mosGetParam($_REQUEST, 'comments', ''), mosGetParam($_REQUEST,
                    'include', ''), 0);
                break;
            case 'remove':
                deleteOrder(mosGetParam($_REQUEST, 'cid'));
                break;
            default:
                showOrders();
        }
        break;
    case 'order_status':
        switch ($task) {
            case 'new':
                editOrderStatus();
                break;
            case 'edit':
                editOrderStatus(mosGetParam($_REQUEST, 'status_id'));
                break;
            case 'save':
                saveOrderStatus(mosGetParam($_REQUEST, 'status_id', 0), 0);
                break;
            case 'apply':
                saveOrderStatus(mosGetParam($_REQUEST, 'status_id', 0), 1);
                break;
            case 'remove':
                deleteOrderStatus(mosGetParam($_REQUEST, 'cid'));
                break;
            case 'cancel':
                showOrderStatus();
                break;
            default:
                showOrderStatus();
                break;
        }
        break;
    case 'attributes':
        switch ($task) {
            case 'new':
                editAttribute(mosGetParam($_REQUEST, 'attr_id'));
                break;
            case 'edit':
                editAttribute(mosGetParam($_REQUEST, 'attr_id'));
                break;
            case 'order':
                orderAttribute(mosGetParam($_REQUEST, 'order'), mosGetParam($_REQUEST, 'id'),
                    mosGetParam($_REQUEST, 'number'));
                break;
            case 'apply':
                saveAttribute(mosGetParam($_REQUEST, 'attr_id', 0), mosGetParam($_REQUEST,
                    'attr_type', 1), mosGetParam($_REQUEST, 'attrib', 0), 1);
                break;
            case 'save':
                saveAttribute(mosGetParam($_REQUEST, 'attr_id', 0), mosGetParam($_REQUEST,
                    'attr_type', 1), mosGetParam($_REQUEST, 'attrib', 0), 0);
                break;
            case 'remove':
                deleteAttribute(mosGetParam($_REQUEST, 'cid'));
                break;
            case 'cancel':
                showAttributes();
                break;
            default:
                showAttributes();
                break;
        }
        break;

    case 'values':
        switch ($task) {
            case 'new':
                editValue(mosGetParam($_REQUEST, 'value_id'), mosGetParam($_REQUEST, 'attr_id'),
                    mosGetParam($_REQUEST, 'op', ''));
                break;
            case 'edit':
                editValue(mosGetParam($_REQUEST, 'value_id'), mosGetParam($_REQUEST, 'attr_id'),
                    mosGetParam($_REQUEST, 'op', ''));
                break;
            case 'apply':
                saveValue(mosGetParam($_REQUEST, 'value_id', 0), mosGetParam($_REQUEST,
                    'attr_id'), mosGetParam($_REQUEST, 'values', 0), 1);
                break;
            case 'save':
                saveValue(mosGetParam($_REQUEST, 'value_id', 0), mosGetParam($_REQUEST,
                    'attr_id'), mosGetParam($_REQUEST, 'values', 0), 0);
                break;
            case 'order':
                orderValue(mosGetParam($_REQUEST, 'order'), mosGetParam($_REQUEST, 'id'),
                    mosGetParam($_REQUEST, 'number'), mosGetParam($_REQUEST, 'attr_id'));
                break;
            case 'remove':
                deleteValue(mosGetParam($_REQUEST, 'cid'));
                showValues(mosGetParam($_REQUEST, 'attr_id'));
                break;
            case 'cancel':
                showValues(mosGetParam($_REQUEST, 'attr_id'));
                break;
            default:
                showValues(mosGetParam($_REQUEST, 'attr_id'));
                break;
        }
        break;

}

function replaceNbsp($string)
{
    return (Jstring::str_ireplace(" ", "_", $string));
}

function replaceToNbsp($string)
{
    return (Jstring::str_ireplace("_", " ", $string));
}

function isWritable($directory)
{
    global $unocartConfig;
    return $return = is_writable($unocartConfig->path . "/" . $directory) ? ('({ "isWrite" : "1", "text" : "' .
        _UNOCART_WRITEABLE . '" })') : ('({ "isWrite" : "0", "text" : "' .
        _UNOCART_NON_WRITEABLE . '"})');
}


function updateMenuTexts()
{
    $database = &unocartFactory::getDBO();
    $arr_links = array('option=com_unocart', 'option=com_unocart&act=categories',
        'option=com_unocart&act=products', 'option=com_unocart&act=manufacturers',
        'option=com_unocart&act=coupons', 'option=com_unocart&act=config',
        'option=com_unocart&act=orders', 'option=com_unocart&act=users',
        'option=com_unocart&act=info', 'option=com_unocart&act=report');
    $arr_names = array(_UNOCART_MENU_MAIN, _UNOCART_MENU_CATEGORIES,
        _UNOCART_MENU_PRODUCTS, _UNOCART_MENU_MANUFACTURERS, _UNOCART_MENU_COUPONS,
        _UNOCART_MENU_CONFIG, _UNOCART_MENU_ORDERS, _UNOCART_MENU_CLIENTS,
        _UNOCART_MENU_INFO, _UNOCART_MENU_WISHLIST);
    foreach ($arr_names as $key => $value) {
        $query = "UPDATE `#__components`
                  SET `name` = '" . $value . "',
                      `admin_menu_alt`  = '" . $value . "'
                  WHERE `admin_menu_link` = '" . $arr_links[$key] . "'";
        $database->setQuery($query);
        $database->query();
    }
}


function saveConfig()
{
    global $unocartConfig;
    $tab = mosGetParam($_POST, 'tab');
    $database = &unocartFactory::getDBO();
    // When checkbox, stavlyu 0 dlya nyh

    $array = array('use_rabatt_code', 'remove_prod_f_wishlist', 'enable_wishlist',
        'allow_reviews_prod', 'allow_reviews_manuf', 'allow_reviews_only_registered');
    if ($tab == 1) {
        foreach ($array as $key => $value) {
            if (!isset($_POST[$value]))
                $_POST[$value] = 0;
        }
    }


    $config = new unocartConfig($database);
    if (!$config->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showConfig();
        exit();
    }
    $config->transformPdfParameters();
    if (is_array($types = mosGetParam($_POST, 'shop_special_type', ''))) {
        $str = '';
        foreach ($types as $type) {
            $str .= $type . ",";
        }
        $str = Jstring::substr($str, 0, Jstring::strlen($str) - 1);
        $config->shop_special_type = $str;
    }
    if (!$config->shop_special_type)
        $config->shop_special_type = 0;
    if (!$config->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        echo $config->_error;
        showConfig();
        exit();
    }


    if (isset($_FILES['header'])) {
        if ($_FILES['header'][size]) {
            @unlink($unocartConfig->path . "images/header.jpg");
            move_uploaded_file($_FILES['header']['tmp_name'], $unocartConfig->path .
                "images/header.jpg");
        }
    }

    if (isset($_FILES['footer'])) {
        if ($_FILES['footer'][size]) {
            @unlink($unocartConfig->path . "images/footer.jpg");
            move_uploaded_file($_FILES['footer']['tmp_name'], $unocartConfig->path .
                "images/footer.jpg");
        }
    }


    //trace ($config, 1);
    // Add to table main_page info pro main_page
    // End Add
    echo messageOutput(_UNOCART_CONFIG_SUCCESS, 'unocart_green');
    foreach ($_POST['description'] as $key => $value) {
        $query = "REPLACE INTO `#__unocart_config_main_page`
                  SET `language` = '" . $key . "', `description` = '" .
            html_entity_decode($_POST['description'][$key]) . "', `meta_title` = '" . $_POST['meta_title'][$key] .
            "', `meta_description` = '" . $_POST['meta_description'][$key] .
            "', `meta_keyword` = '" . $_POST['meta_keyword'][$key] . "', `agb` = '" .
            html_entity_decode($_POST['agb'][$key]) . "', `return_policy` = '" .
            html_entity_decode($_POST['return_policy'][$key]) . "'";
        $database->setQuery($query);
        $database->query();
    }
    $link = 'index2.php?option=com_unocart&act=config';
    if ($tab == 1) {
        if ($unocartConfig->mainLanguage != mosGetParam($_POST, 'mainLanguage')) {
            $link = 'index.php?option=com_unocart&act=config&task=updateMenu';
        }
    }

    mosRedirect($link);
}

function showConfig()
{
    global $unocartConfig, $format_currency, $shop_type;
    $database = &unocartFactory::getDBO();
    $currencies = unocartCurrency::getAllCurrencies();
    $languages = getAllAdminLanguages();
    $languages2 = getAllLanguages();
    $countries = unocartCountry::getAllCountries();
    $first = mosHTML::makeOption(0, _UNOCART_SELECT, 'country_id', 'country_name');
    array_unshift($countries, $first);
    $order_status = unocartOrderStatus::getAllOrders();
    $lists['status'] = mosHTML::selectList($order_status, 'default_status_order',
        'class = "inputbox" size = "1"', 'status_id', 'status_name', $unocartConfig->
        default_status_order);
    $lists['currencies'] = mosHTML::selectList($currencies, 'mainCurrency',
        'class = "inputbox" size = "1"', 'currency_id', 'currency_name', $unocartConfig->
        mainCurrency);
    $lists['countries'] = mosHTML::selectList($countries, 'store_country',
        'class = "inputbox" size = "1"', 'country_id', 'country_name', $unocartConfig->
        store_country);
    $lists['languages'] = $languages;
    $lists['languages_2'] = mosHTML::selectList(getAllLanguages(), 'defaultLanguage',
        'class = "inputbox" size = "1"', 'language', 'language', $unocartConfig->
        defaultLanguage);


    if ($unocartConfig->shop_special_type) {
        foreach ($unocartConfig->shop_special_type as $key => $value) {
            $types_active[]->id_type = $value;
        }
    } else {
        $types_active = null;
    }

    foreach ($shop_type as $key => $value) {
        $types[] = mosHTML::makeOption($key, $value, 'id_type', 'type');
    }
    $lists['shop_special_type'] = mosHTML::selectList($types, 'shop_special_type[]',
        'size = "5" multiple = "multiple"', 'id_type', 'type', $types_active);

    $i = 0;
    foreach ($format_currency as $key => $value) {
        $currenc[$i]->id_cur = $key;
        $currenc[$i++]->format = $value;
    }
    $lists['format_currency'] = mosHTML::selectList($currenc, 'currency_format',
        'class = "inputbox" size = "1"', 'id_cur', 'format', $unocartConfig->
        currency_format);

    $all_languages = getAllLanguages();
    $query = "SELECT main_page.*
              FROM `#__unocart_config_main_page` AS main_page";
    $database->setQuery($query);
    $rows = $database->loadObjectList();

    // Zaganyau vsi language in masyv
    foreach ($all_languages as $key => $value) {
        $lang[] = $value->language;
    }

    $langs = array();
    foreach ($rows as $key => $value) {
        if (!in_array($value->language, $lang)) {
            unset($rows[$key]);
        } else {
            $langs[] = $value->language;
        }
    }
    unset($lang);

    foreach ($all_languages as $lang) {
        if (!in_array($lang->language, $langs)) {
            $object->language = $lang->language;
            $object->description = $object->meta_title = $object->meta_keyword = $object->
                meta_description = $object->agb = $object->return_policy = '';
            $rows[] = $object;
            unset($object);
        }
    }
    $lists['descr'] = $rows;
    $tab = mosGetParam($_REQUEST, 'tab', 0);
    if ($tab) {
        call_user_func(array("HTML_UNOCART", 'showConfigTab' . $tab), $unocartConfig, $lists);
    } else {
        HTML_UNOCART::showConfig($unocartConfig, $lists);
    }
}

function previewPdf()
{
    global $unocartConfig;
    require_once (JPATH_BASE . "/components/com_unocart/pdf/pdf.php");
    $order->pdf_file = generatePdf($order, $cart, $unocartConfig);
    header("Location: " . $unocartConfig->live_path . "pdf/files/" . $order->
        pdf_file);
}

function getAllAdminLanguages()
{
    global $unocartConfig;
    $path = $unocartConfig->admin_path . '/lang';
    $handle = opendir($path);
    $name_select = 'mainLanguage';
    $name_option = 'mainLang';
    while (false !== ($file = readdir($handle))) {
        if ($file == '..' || is_dir($file) || $file == 'index.html')
            continue;
        $file = Jstring::substr($file, 6, Jstring::strlen($file) - 10);
        $languages[] = mosHTML::makeOption($file, $file, $name_option, $name_select);
    }
    return mosHTML::selectList($languages, $name_select, 'class="inputbox" size="1"',
        $name_option, $name_select, $unocartConfig->mainLanguage);
}

function getParentCategory($category_id)
{
    $database = &unocartFactory::getDBO();
    $query = "SELECT a.category_parent_id
   	           FROM `#__unocart_categories` AS a
   	           WHERE a.category_id = '" . $category_id . "'";
    $database->setQuery($query);
    return $database->loadResult();
}

// Povertae spysok categories, yaki znahodyatsya na odnomu rivni iz potochnoju
function getAllCategoriesLevel($parentId, $currentOrdering = 0)
{
    global $unocartConfig;
    $rows = unocartCategory::getAllCategoriesDescription($parentId);
    $first[] = mosHTML::makeOption('0', _UNOCART_ORDERING_FIRST, 'category_ordering',
        'category_name');
    $rows = array_merge($first, $rows);
    $currentOrdering = (!$currentOrdering) ? ($rows[count($rows) - 1]->
        category_ordering) : ($currentOrdering);
    return (mosHTML::selectList($rows, 'category_ordering',
        'class="inputbox" size="1"', 'category_ordering', 'category_name', $currentOrdering));
}

function showTreeCategory($parentId)
{
    global $unocartConfig;
    $categories = unocartCategory::getAllCategoriesDescription($parentId);
    $parentTop->category_id = 0;
    $parentTop->category_name = _UNOCART_TOP_LEVEL;
    $categories_select = buildTreeCategory(0);
    array_unshift($categories_select, $parentTop);
    $lists['treecategories'] = mosHTML::selectList($categories_select,
        'category_tree_id', 'class="inputbox" id = "category_ordering" size="1" onchange = "changeCategoryHref(this.value)"',
        'category_id', 'category_name', $parentId);
    $lists['parentid'] = $parentId;
    HTML_UNOCART::showTreeCategories($categories, $lists);
}

function orderCategory($order, $cid, $number)
{
    $database = &unocartFactory::getDBO();
    $category = new unocartCategory($database);
    $category->load($cid);
    switch ($order) {
        case 'up':
            $query = "SELECT a.category_id, a.category_ordering
                   FROM `#__unocart_categories` AS a
                   WHERE a.category_ordering < '" . $number .
                "' AND a.category_parent_id = '" . $category->category_parent_id . "'
                   ORDER BY a.category_ordering DESC
                   LIMIT 1";
            break;
        case 'down':
            $query = "SELECT a.category_id, a.category_ordering
                   FROM `#__unocart_categories` AS a
                   WHERE a.category_ordering > '" . $number .
                "' AND a.category_parent_id = '" . $category->category_parent_id . "'
                   ORDER BY a.category_ordering ASC
                   LIMIT 1";
    }
    $database->setQuery($query);
    $database->loadObject($row);
    $query1 = "UPDATE `#__unocart_categories` AS a
                 SET a.category_ordering = '" . $row->category_ordering . "'
                 WHERE a.category_id = '" . $cid . "'";
    $query2 = "UPDATE `#__unocart_categories` AS a
                 SET a.category_ordering = '" . $number . "'
                 WHERE a.category_id = '" . $row->category_id . "'";
    $database->setQuery($query1);
    $database->query();

    $database->setQuery($query2);
    $database->query();

    showTreeCategory(mosGetParam($_REQUEST, 'catid', 0));

}
/*
function orderLanguage($order,$cid,$number) {
$database = &unocartFactory::getDBO();
$language = new unocartLanguage($database);
$language->load($cid);
switch ($order) {
case 'up':
$query = "SELECT a.language_id, a.language_ordering
FROM `#__unocart_languages` AS a
WHERE a.language_ordering < '" . $number . "'
ORDER BY a.language_ordering DESC
LIMIT 1";
break;
case 'down':
$query = "SELECT a.language_id, a.language_ordering
FROM `#__unocart_languages` AS a
WHERE a.language_ordering > '" . $number . "'
ORDER BY a.language_ordering ASC
LIMIT 1";
}

$database->setQuery($query);
@$database->loadObject($row);


$query1 = "UPDATE `#__unocart_languages` AS a
SET a.language_ordering = '" . $row->language_ordering . "'
WHERE a.language_id = '" . $cid . "'";
$query2 = "UPDATE `#__unocart_languages` AS a
SET a.language_ordering = '" . $number . "'
WHERE a.language_id = '" . $row->language_id . "'";
$database->setQuery($query1);
$database->query();

$database->setQuery($query1);
$database->query();

showLanguages();
}


function reorderLanguage(&$language) {
$database = &unocartFactory::getDBO();
$query = "UPDATE `#__unocart_languages`
SET `language_ordering` = language_ordering + 1
WHERE `language_ordering` > '" . $language->language_ordering . "'";
$database->setQuery($query);
$database->query();
$language->language_ordering++;
}
*/
function reorderCategory(&$category)
{
    $database = &unocartFactory::getDBO();
    $query = "UPDATE `#__unocart_categories`
                SET `category_ordering` = category_ordering + 1
                WHERE `category_parent_id` = '" . $category->category_parent_id .
        "' AND `category_ordering` > '" . $category->category_ordering . "'";
    $database->setQuery($query);
    $database->query();
    $category->category_ordering++;
}

function getFileName($name)
{
    // Get Extension
    $ext_file = Jstring::strtolower(Jstring::substr($name, Jstring::strrpos($name, ".")));
    // Generate name file
    $name_file = md5(uniqid(rand(), true));
    return $name_file . $ext_file;
}

function saveCategory($apply)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $category = new unocartCategory($database);
    if (!$category->category_add_date)
        $category->category_add_date = date("Y-m-d H:i:s");
    if (!isset($_POST['category_publish']))
        $_POST['category_publish'] = 0;
    if (!$category->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showTreeCategory();
        exit();
    }

    require_once ($unocartConfig->admin_path . '/thumbnail_images.class.php');

    foreach ($_REQUEST as $key => $value)
        $$key = mosGetParam($_POST, $key, "", _MOS_ALLOWRAW);
    $name_file = getFileName($_FILES['category_image']['name']);
    $path_image = $unocartConfig->image_category_path . "/" . $name_file;
    if ($_FILES['category_image']['name']) {
        if (move_uploaded_file($_FILES['category_image']['tmp_name'], $path_image)) {
            if ($category->category_image) {
                unlink($unocartConfig->image_category_path . "/" . $category->category_image);
            }
            // Get the image size
            if ($size_im_category == 3) {
                list($category_width_image, $category_height_image, $type, $attr) = getimagesize($path_image);
            }
            $img = new thumbnail_images();
            $img->PathImgOld = $path_image;
            $img->PathImgNew = $path_image;
            $img->NewWidth = $category_width_image;
            $img->NewHeight = $category_height_image;
            if (!$img->create_thumbnail_images()) {
                echo "error";
                return;
            }
        }
        $category->category_image = $name_file;
    }

    reorderCategory($category);
    if (!$category->store()) {
        echo _UNOCART_ERROR_SAVE_DATABASE;
        exit();
    }


    foreach ($category_name as $key => $value) {
        $query = "REPLACE INTO `#__unocart_categories_description`
                  SET `category_id` = '" . $category->category_id .
            "', `language` = '" . $key . "', `category_name` = '" . replaceToNbsp($category_name[$key]) .
            "', `category_description` = '" . html_entity_decode($category_description[$key]) .
            "', `category_meta_title` = '" . $category_meta_title[$key] .
            "', `category_meta_description` = '" . $category_meta_description[$key] .
            "', `category_meta_keyword` = '" . $category_meta_keyword[$key] . "'";
        $database->setQuery($query);
        $success = ($edit) ? (_UNOCART_CATEGORY_SUCC_UPDATE) : (_UNOCART_CATEGORY_SUCC_ADDED);
        $mosmsg = ($database->query()) ? ($success) : (_UNOCART_ERROR_SAVE_DATABASE);
    }

    mosRedirect(($apply) ? ('index2.php?option=com_unocart&act=categories&task=edit&catid=' .
        $category->category_id . "&mosmsg=" . $mosmsg) : ('index2.php?option=com_unocart&act=categories&catid=' .
        $parentid));
}

function getTemplates($folder, $selected)
{
    global $unocartConfig;
    if ($folder == 'category') {
        $name_select = 'category_template';
        $name_option = 'cat_template';
    } else
        if ($folder == 'product') {
            $name_select = 'product_template';
            $name_option = 'prod_template';
        }
    $path = $unocartConfig->path . '/smarty/templates/' . $folder;
    $handle = opendir($path);
    while (false !== ($file = readdir($handle))) {
        if ($file == '..' || is_dir($file) || $file == 'index.html')
            continue;
        $templates[] = mosHTML::makeOption($file, $file, $name_option, $name_select);
    }
    return mosHTML::selectList($templates, $name_select, 'class="inputbox" size="1"',
        $name_option, $name_select, $selected);
}

function generateSelectSorting($field_id, $name_select)
{
    global $ordering_category;
    foreach ($ordering_category as $key => $value) {
        $field->id = $key;
        $field->name = $value;
        $select[] = $field;
        $field = null;
    }
    return mosHTML::selectList($select, $name_select, '', 'id', 'name', $field_id);
}

function editCategory($cid = null, $parentid = 0)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $category = new unocartCategory($database);
    $category->load($cid);
    if ($cid) {
        $all_languages = getAllLanguages();
        $query = "SELECT categ_descr.*
                  FROM `#__unocart_categories_description` AS categ_descr
                  WHERE categ_descr.category_id = '" . $cid . "'";
        $database->setQuery($query);
        $rows = $database->loadObjectList();

        // Zaganyau vsi language in masyv
        foreach ($all_languages as $key => $value) {
            $lang[] = $value->language;
        }

        $langs = array();
        foreach ($rows as $key => $value) {
            if (!in_array($value->language, $lang)) {
                unset($rows[$key]);
            } else {
                $langs[] = $value->language;
            }
        }
        unset($lang);

        foreach ($all_languages as $lang) {
            if (!in_array($lang->language, $langs)) {
                $object->language = $lang->language;
                $object->category_id = $descr[0]->category_id;
                $object->category_name = $object->category_description = $object->
                    category_meta_title = $object->category_meta_description = $object->
                    category_meta_keyword = '';
                $rows[] = $object;
                unset($object);
            }
        }
        $edit = 1;
    } else {
        $rows = getAllLanguages();
        $edit = 0;
        $category->products_sorting = 1;
        $category->products_sorting2 = 1;
    }

    $cats = $rows;
    if ($category->category_parent_id != '') {
        $rows = getAllCategoriesLevel($category->category_parent_id, $category->
            category_ordering);
        $parentid = $category->category_parent_id;
    } else {
        $rows = getAllCategoriesLevel($parentid);
    }

    $lists['writeable'] = (is_writable($unocartConfig->image_category_path)) ? ($unocartConfig->
        image_category_path . '::' . messageOutput(_UNOCART_WRITEABLE, 'unocart_green')) : ($unocartConfig->
        image_category_path . '::' . messageOutput(_UNOCART_NON_WRITEABLE));
    $lists['templates'] = getTemplates('category', $category->category_template);
    $lists['onelevel'] = $rows;
    $parentTop->category_id = 0;
    $parentTop->category_name = _UNOCART_TOP_LEVEL;
    $categories = buildTreeCategory(0);
    array_unshift($categories, $parentTop);


    $orderingtype[] = mosHTML::makeOption(1, _UNOCART_MANUAL, 'ordering_type_id',
        'ordering_type_value');
    $orderingtype[] = mosHTML::makeOption(2, _UNOCART_ALPH, 'ordering_type_id',
        'ordering_type_value');

    $lists['orderingtype'] = mosHTML::selectList($orderingtype, 'category_ordertype',
        'class = "inputbox" size = "1"', 'ordering_type_id', 'ordering_type_value', $category->
        category_ordertype);


    $lists['treecategories'] = mosHTML::selectList($categories, 'category_parent_id',
        'class="inputbox" id = "category_ordering" size="1" onchange = "changeCategory()"',
        'category_id', 'category_name', $parentid);
    $lists['parentid'] = $parentid;
    $lists['product_sorting'] = generateSelectSorting($category->products_sorting,
        'products_sorting');
    $lists['product_sorting2'] = generateSelectSorting($category->products_sorting2,
        'products_sorting2');
    HTML_UNOCART::editCategory($category, $cats, $lists, $edit);
}

function getNameProductById($id)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $query = "SELECT a.product_name
               FROM `#__unocart_products_description` AS a
   	           WHERE a.product_id = '" . $id . "' AND a.language = '" . $unocartConfig->
        cur_lang . "'";
    $database->setQuery($query);
    return $database->loadResult();
}


function getManufacturerById($id)
{
    $database = &unocartFactory::getDBO();
    $man = new unocartManufacturer($database);
    $man->load($id);
    return $man->manufacturer_name;
}


function deleteCategory($cid)
{
    $database = &unocartFactory::getDBO();
    $text = '';
    foreach ($cid as $key => $value) {
        $category = new unocartCategory($database);
        $category->load($value);
        $name_category = $category->getName();
        if ($category->getCountProducts()) {
            $text .= messageOutput(sprintf(_UNOCART_CATEGORY_NO_DELETED, $name_category));
            continue;
        }
        $category->deleteCategory();
        $text .= messageOutput(sprintf(_UNOCART_CATEGORY_DELETED, $name_category));
    }
    echo $text;
    showTreeCategory(mosGetParam($_REQUEST, 'category_tree_id', 0));
}

function publishCategory($cid, $flag)
{
    $database = &unocartFactory::getDBO();
    foreach ($cid as $key => $value) {
        $query = "UPDATE `#__unocart_categories`
                  SET `category_publish` = '" . $flag . "'
                  WHERE `category_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();
    }
    showTreeCategory(mosGetParam($_REQUEST, 'category_tree_id', 0));
}
/*
function publishLanguage($cid,$flag) {
$database = &unocartFactory::getDBO();
$query = '';
foreach ($cid as $key => $value) {
$query = "UPDATE `#__unocart_languages`
SET `language_publish` = '" . $flag . "'
WHERE `language_id` = '" . $value . "'";
$database->setQuery($query);
$database->query();
}
showLanguages();
}

function deleteLanguage($cid) {
$database = &unocartFactory::getDBO();
$query = '';
$text = '';


foreach ($cid as $key => $value) {
$count_queries = 0;
$query = "DELETE FROM `#__unocart_languages`
WHERE `language_id` = '" . $value . "'";
$database->setQuery($query);
if($database->query())
$count_queries++;

$query = "DELETE FROM `#__unocart_categories_description`
WHERE `language_id` = '" . $value . "'";
$database->setQuery($query);
if($database->query())
$count_queries++;

$query = "DELETE FROM `#__unocart_products_description`
WHERE `language_id` = '" . $value . "'";
$database->setQuery($query);
if($database->query())
$count_queries++;

$query = "DELETE FROM `#__unocart_config_main_page`
WHERE `language_id` = '" . $value . "'";
$database->setQuery($query);
if($database->query())
$count_queries++;

if($count_queries == 4)
$text .= messageOutput(_UNOCART_LANGUAGE_DELETED);
else
$text .= messageOutput(_UNOCART_ERROR_DELETE_LANGUAGE);
}
echo $text;
showLanguages();
}
*/
function showCurrencies()
{
    $database = &unocartFactory::getDBO();
    $rows = unocartCurrency::getAllCurrencies(0);
    HTML_UNOCART::showCurrencies($rows);
}

function editCurrency($currency_id = null)
{
    $database = &unocartFactory::getDBO();
    $currency = new unocartCurrency($database);
    $currency->load($currency_id);
    $first[] = mosHTML::makeOption('0', _UNOCART_ORDERING_FIRST, 'currency_ordering',
        'currency_name');
    $rows = array_merge($first, unocartCurrency::getAllCurrencies());
    $lists['order_currencies'] = mosHTML::selectList($rows, 'currency_ordering',
        'class="inputbox" size="1"', 'currency_ordering', 'currency_name', $currency->
        currency_ordering);
    $edit = ($currency_id) ? ($edit = 1) : ($edit = 0);
    HTML_UNOCART::editCurrency($currency, $lists, $edit);
}

function saveCurrency($currency_id, $apply)
{
    $database = &unocartFactory::getDBO();
    $currency = new unocartCurrency($database);
    if (!$currency->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showCurrencies();
        exit();
    }

    reorderCurrency($currency);
    if (!$currency->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        showCurrencies();
        exit();
    }
    mosRedirect(($apply) ? ('index2.php?option=com_unocart&act=currencies&task=edit&currency_id=' .
        $currency->currency_id) : ('index2.php?option=com_unocart&act=currencies'));
}

function reorderCurrency(&$currency)
{
    $database = &unocartFactory::getDBO();
    $query = "UPDATE `#__unocart_currencies`
                SET `currency_ordering` = currency_ordering + 1
                WHERE `currency_ordering` > '" . $currency->currency_ordering .
        "'";
    $database->setQuery($query);
    $database->query();
    $currency->currency_ordering++;
}
/* Old function non used
function addToAllProductsCurrency($currency_id){
$database = &unocartFactory::getDBO();
$query = "SELECT pr.product_id
FROM `#__unocart_products` AS pr";
$database->setQuery($query);
$all_pr = $database->loadObjectList();
$query = '';
if (count($all_pr)){
foreach ($all_pr as $pr){
$query .= "INSERT INTO `#__unocart_products_price`
SET product_id = '" . $pr->product_id . "', `currency_id` = '" . $currency_id . "'; ";
}
}
$database->setQuery($query);
$database->query_batch();
}
*/

function orderCurrency($order, $cid, $number)
{
    $database = &unocartFactory::getDBO();
    $currency = new unocartCurrency($database);
    $currency->load($cid);
    switch ($order) {
        case 'up':
            $query = "SELECT a.currency_id, a.currency_ordering
                   FROM `#__unocart_currencies` AS a
                   WHERE a.currency_ordering < '" . $number . "'
                   ORDER BY a.currency_ordering DESC
                   LIMIT 1";
            break;
        case 'down':
            $query = "SELECT a.currency_id, a.currency_ordering
                   FROM `#__unocart_currencies` AS a
                   WHERE a.currency_ordering > '" . $number . "'
                   ORDER BY a.currency_ordering ASC
                   LIMIT 1";
    }

    $database->setQuery($query);
    @$database->loadObject($row);


    $query1 = "UPDATE `#__unocart_currencies` AS a
                 SET a.currency_ordering = '" . $row->currency_ordering . "'
                 WHERE a.currency_id = '" . $cid . "'";
    $query2 = "UPDATE `#__unocart_currencies` AS a
                 SET a.currency_ordering = '" . $number . "'
                 WHERE a.currency_id = '" . $row->currency_id . "'";
    $database->setQuery($query1);
    $database->query();
    $database->setQuery($query2);
    $database->query();
    showCurrencies();
}

function deleteCurrency($cid)
{
    $database = &unocartFactory::getDBO();
    $query = '';
    $text = '';


    foreach ($cid as $key => $value) {
        $query = "DELETE FROM `#__unocart_currencies`
                   WHERE `currency_id` = '" . $value . "'";
        /* Old non used
        $query .= "DELETE FROM `#__unocart_products_price`
        WHERE `currency_id` = '" . $value . "'; ";
        */
        $database->setQuery($query);
        if ($database->query())
            $text .= messageOutput(_UNOCART_CURRENCY_DELETED);
        else
            $text .= messageOutput(_UNOCART_CURRENCY_ERROR_DELETED);

    }
    echo $text;
    showCurrencies();
}

function publishCurrency($cid, $flag)
{
    $database = &unocartFactory::getDBO();
    foreach ($cid as $key => $value) {
        $query = "UPDATE `#__unocart_currencies`
                   SET `currency_publish` = '" . $flag . "'
                   WHERE `currency_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();
    }
    showCurrencies();
}


function showCountries()
{
    $database = &unocartFactory::getDBO();
    $limitstart = mosGetParam($_REQUEST, 'limitstart', 0);
    $limit = mosGetParam($_REQUEST, 'limit', 25);
    $total = unocartCountry::getCountAllCountries();
    require_once (JPATH_BASE . '/administrator/includes/pageNavigation.php');
    $pageNav = new mosPageNav($total, $limitstart, $limit);
    $rows = unocartCountry::getAllCountries(0, $pageNav->limitstart, $pageNav->
        limit);
    HTML_UNOCART::showCountries($rows, $pageNav);
}

function editCountry($country_id = null)
{
    $database = &unocartFactory::getDBO();
    $country = new unocartCountry($database);
    $country->load($country_id);
    $first[] = mosHTML::makeOption('0', _UNOCART_ORDERING_FIRST, 'country_ordering',
        'country_name');
    $rows = array_merge($first, unocartCountry::getAllCountries());
    $lists['order_countries'] = mosHTML::selectList($rows, 'country_ordering',
        'class="inputbox" size="1"', 'country_ordering', 'country_name', $country->
        country_ordering);
    $edit = ($country_id) ? ($edit = 1) : ($edit = 0);
    HTML_UNOCART::editCountry($country, $lists, $edit);
}

function saveCountry($country_id, $apply)
{
    $database = &unocartFactory::getDBO();
    $country = new unocartCountry($database);
    if (!$country->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showCountries();
        exit();
    }


    if (!$country->country_publish)
        $country->country_publish = 0;
    reorderCountry($country);
    if (!$country->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        showCountries();
        exit();
    }
    mosRedirect(($apply) ? ('index2.php?option=com_unocart&act=countries&task=edit&country_id=' .
        $country->country_id) : ('index2.php?option=com_unocart&act=countries'));
}

function reorderCountry(&$country)
{
    $database = &unocartFactory::getDBO();
    $query = "UPDATE `#__unocart_countries`
                SET `country_ordering` = country_ordering + 1
                WHERE `country_ordering` > '" . $country->country_ordering . "'";
    $database->setQuery($query);
    $database->query();
    $country->country_ordering++;
}


function orderCountry($order, $cid, $number)
{
    $database = &unocartFactory::getDBO();
    $country = new unocartCountry($database);
    $country->load($cid);
    switch ($order) {
        case 'up':
            $query = "SELECT a.country_id, a.country_ordering
                   FROM `#__unocart_countries` AS a
                   WHERE a.country_ordering < '" . $number . "'
                   ORDER BY a.country_ordering DESC
                   LIMIT 1";
            break;
        case 'down':
            $query = "SELECT a.country_id, a.country_ordering
                   FROM `#__unocart_countries` AS a
                   WHERE a.country_ordering > '" . $number . "'
                   ORDER BY a.country_ordering ASC
                   LIMIT 1";
    }

    $database->setQuery($query);
    @$database->loadObject($row);


    $query1 = "UPDATE `#__unocart_countries` AS a
                 SET a.country_ordering = '" . $row->country_ordering . "'
                 WHERE a.country_id = '" . $cid . "'";
    $query2 = "UPDATE `#__unocart_countries` AS a
                 SET a.country_ordering = '" . $number . "'
                 WHERE a.country_id = '" . $row->country_id . "'";
    $database->setQuery($query1);
    $database->query();
    $database->setQuery($query2);
    $database->query();
    showCountries();
}

function deleteCountry($cid)
{
    $database = &unocartFactory::getDBO();
    $query = '';
    $text = '';


    foreach ($cid as $key => $value) {
        $query = "DELETE FROM `#__unocart_countries`
                   WHERE `country_id` = '" . $value . "'";
        $database->setQuery($query);
        if ($database->query())
            $text .= messageOutput(_UNOCART_COUNTRY_DELETED);
        else
            $text .= messageOutput(_UNOCART_COUNTRY_ERROR_DELETED);

    }
    echo $text;
    showCountries();
}

function publishCountry($cid, $flag)
{
    $database = &unocartFactory::getDBO();
    foreach ($cid as $key => $value) {
        $query = "UPDATE `#__unocart_countries`
                   SET `country_publish` = '" . $flag . "'
                   WHERE `country_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();
    }
    showCountries();
}


function showCoupons()
{
    $database = &unocartFactory::getDBO();
    $rows = unocartCoupon::getAllCoupons(0);
    HTML_UNOCART::showCoupons($rows);
}

function editCoupon($coupon_id = null)
{
    $database = &unocartFactory::getDBO();
    $coupon = new unocartCoupon($database);
    $coupon->load($coupon_id);
    $edit = ($coupon_id) ? ($edit = 1) : ($edit = 0);
    $arr_type_coupon[0]->coupon_type = 0;
    $arr_type_coupon[0]->coupon_value = _UNOCART_COUPON_PERCENT;

    $arr_type_coupon[1]->coupon_type = 1;
    $arr_type_coupon[1]->coupon_value = _UNOCART_COUPON_ABS_VALUE;

    $lists['coupon_type'] = mosHTML::radioList($arr_type_coupon, 'coupon_type', '',
        $coupon->coupon_type, 'coupon_type', 'coupon_value');
    HTML_UNOCART::editCoupon($coupon, $lists, $edit);
}

function saveCoupon($coupon_id, $apply)
{
    $database = &unocartFactory::getDBO();
    $coupon = new unocartCoupon($database);
    if (!$coupon->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showCoupons();
        return;
    }

    if ($coupon->existCoupon()) {
        echo messageOutput(_UNOCART_ERROR_COUPON_EXIST);
        showCoupons();
        return;
    }


    if (!$coupon->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        showCoupons();
        return;
    }
    mosRedirect(($apply) ? ('index2.php?option=com_unocart&act=coupons&task=edit&coupon_id=' .
        $coupon->coupon_id) : ('index2.php?option=com_unocart&act=coupons'));
}

function deleteCoupon($cid)
{
    $database = &unocartFactory::getDBO();
    $query = '';
    $text = '';


    foreach ($cid as $key => $value) {
        $query = "DELETE FROM `#__unocart_coupons`
                   WHERE `coupon_id` = '" . $value . "'";
        $database->setQuery($query);
        if ($database->query())
            $text .= messageOutput(_UNOCART_COUPON_DELETED);
        else
            $text .= messageOutput(_UNOCART_COUPON_ERROR_DELETED);
    }
    echo $text;
    showCoupons();
}

function publishCoupon($cid, $flag)
{
    $database = &unocartFactory::getDBO();
    foreach ($cid as $key => $value) {
        $query = "UPDATE `#__unocart_coupons`
                   SET `coupon_publish` = '" . $flag . "'
                   WHERE `coupon_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();
    }
    showCoupons();
}


function showPaymentMethods()
{
    $database = &unocartFactory::getDBO();
    $rows = unocartPaymentMethod::getAllPaymentMethods(0);
    HTML_UNOCART::showPaymentMethods($rows);
}

function editPaymentMethod($payment_id = null)
{
    global $payment_type;
    $database = &unocartFactory::getDBO();
    $payment = new unocartPaymentMethod($database);
    $payment->load($payment_id);
    $parseString = new parseString($payment->payment_params);
    $params = $parseString->parseStringToParams();
    $edit = ($payment_id) ? ($edit = 1) : ($edit = 0);
    foreach ($payment_type as $key => $value) {
        $payms[] = mosHTML::makeOption($key, $value, 'payment_type', 'payment_type_name');
    }
    if ($edit) {
        require_once (JPATH_BASE . "/components/com_unocart/payments/" . $payment->
            payment_class . ".php");
        $lists['html'] = call_user_func(array($payment->payment_class,
            'showAdminFormParams'), $params);
    } else {
        $lists['html'] = '';
    }
    $lists['type_payment'] = mosHTML::selectList($payms, 'payment_type',
        'class = "inputbox" size ="1"', 'payment_type', 'payment_type_name', $payment->
        payment_type);
    HTML_UNOCART::editPaymentMethod($payment, $edit, $params, $lists);
}

function savePaymentMethod($payment_id, $apply)
{
    $database = &unocartFactory::getDBO();
    $payment = new unocartPaymentMethod($database);
    if (!$payment->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showPaymentMethods();
        exit();
    }

    if (isset($_POST['pm_params'])) {
        $parseString = new parseString($_POST['pm_params']);
        $payment->payment_params = $parseString->splitParamsToString();
    }
    $payment->payment_description = html_entity_decode($payment->
        payment_description);

    if (!$payment->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        echo $payment->getError();
        showPaymentMethods();
        exit();
    }
    mosRedirect(($apply) ? ("index2.php?option=com_unocart&act=payments&task=edit&payment_id=" .
        $payment->payment_id) : ("index2.php?option=com_unocart&act=payments"));
}

function deletePaymentMethod($cid)
{
    $database = &unocartFactory::getDBO();
    $text = '';
    foreach ($cid as $key => $value) {
        $query = "DELETE FROM `#__unocart_payment_method`
                  WHERE `payment_id` = '" . $value . "'";
        $database->setQuery($query);
        if ($database->query())
            $text .= messageOutput(_UNOCART_PAYMENT_DELETED);
        else
            $text .= messageOutput(_UNOCART_ERROR_PAYMENT_DELETED);
    }
    echo $text;
    showPaymentMethods();
}

function publishPaymentMethod($cid, $flag)
{
    $database = &unocartFactory::getDBO();
    foreach ($cid as $key => $value) {
        $query = "UPDATE `#__unocart_payment_method`
                   SET `payment_publish` = '" . $flag . "'
                   WHERE `payment_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();
    }
    showPaymentMethods();
}

function orderPaymentMethod($order, $cid, $number)
{
    $database = &unocartFactory::getDBO();
    $currency = new unocartPaymentMethod($database);
    $currency->load($cid);
    switch ($order) {
        case 'up':
            $query = "SELECT a.payment_id, a.payment_ordering
                   FROM `#__unocart_payment_method` AS a
                   WHERE a.payment_ordering < '" . $number . "'
                   ORDER BY a.payment_ordering DESC
                   LIMIT 1";
            break;
        case 'down':
            $query = "SELECT a.payment_id, a.payment_ordering
                   FROM `#__unocart_payment_method` AS a
                   WHERE a.payment_ordering > '" . $number . "'
                   ORDER BY a.payment_ordering ASC
                   LIMIT 1";
    }
    $database->setQuery($query);
    @$database->loadObject($row);
    $query1 = "UPDATE `#__unocart_payment_method` AS a
                 SET a.payment_ordering = '" . $row->payment_ordering . "'
                 WHERE a.payment_id = '" . $cid . "'";
    $query2 = "UPDATE `#__unocart_payment_method` AS a
                 SET a.payment_ordering = '" . $number . "'
                 WHERE a.payment_id = '" . $row->payment_id . "'";
    $database->setQuery($query1);
    $database->query();
    $database->setQuery($query2);
    $database->query();

    showPaymentMethods();
}


function showShippingMethods()
{
    $database = &unocartFactory::getDBO();
    $rows = unocartShippingMethod::getAllShippingMethods(0);
    HTML_UNOCART::showShippingMethods($rows);
}

function showShippingMethodsPrices()
{
    $rows = unocartShippingMethodPrice::getAllShippingMethodsPrices(0);
    HTML_UNOCART::showShippingMethodsPrices($rows);
}

function editShippingMethod($shipping_id = null)
{
    $database = &unocartFactory::getDBO();
    $shipping = new unocartShippingMethod($database);
    $shipping->load($shipping_id);
    $edit = ($shipping_id) ? ($edit = 1) : ($edit = 0);
    HTML_UNOCART::editShippingMethod($shipping, $edit);
}

function editShippingMethodPrice($sh_pr_method_id)
{
    $database = &unocartFactory::getDBO();
    $sh_method_price = new unocartShippingMethodPrice($database);
    $sh_method_price->load($sh_pr_method_id);
    $sh_method_price->prices = $sh_method_price->getPrices();
    $all_taxes = unocartTax::getAllTaxes();
    $list_tax = array();
    $list_tax[] = mosHTML::makeOption('0', _UNOCART_SELECT, 'tax_id', 'tax_name');
    foreach ($all_taxes as $tax) {
        $list_tax[] = mosHTML::makeOption($tax->tax_id, $tax->tax_name . ' {' . $tax->
            tax_value . '%)', 'tax_id', 'tax_name');
    }

    $lists['taxes'] = mosHTML::selectList($list_tax, 'shipping_tax_id',
        'class = "inputbox" size = "1" id = "shipping_tax_id"', 'tax_id', 'tax_name', $sh_method_price->
        shipping_tax_id);
    $lists['shipping_methods'] = mosHTML::selectList(unocartShippingMethod::
        getAllShippingMethods(), 'shipping_method_id', 'class = "inputbox" size = "1"',
        'shipping_id', 'shipping_name', $sh_method_price->shipping_method_id);
    $lists['countries'] = mosHTML::selectList(unocartCountry::getAllCountries(),
        'shipping_countries_id[]',
        'class = "inputbox" size = "10", multiple = "multiple"', 'country_id',
        'country_name', $sh_method_price->getCountries());
    HTML_UNOCART::editShippingMethodPrice($sh_method_price, $lists);
}

function deleteShippingMethodPrice($cid)
{
    $database = &unocartFactory::getDBO();
    $query = '';
    $text = '';
    foreach ($cid as $key => $value) {
        $query = "DELETE FROM `#__unocart_shipping_method_price`
                  WHERE `sh_pr_method_id` = '" . $value . "'";
        $database->setQuery($query);
        if ($database->query()) {
            $text .= messageOutput(_UNOCART_SHIPPING_DELETED);
            $query = "DELETE FROM `#__unocart_shipping_method_price_weight`
                   	  WHERE `sh_pr_method_id` = '" . $value . "'";
            $database->setQuery($query);
            $database->query();

            $query = "DELETE FROM `#__unocart_shipping_method_price_countries`
                   	  WHERE `sh_pr_method_id` = '" . $value . "'";
            $database->setQuery($query);
            $database->query();
        } else {
            $text .= messageOutput(_UNOCART_ERROR_SHIPPING_DELETED);
        }
    }
    echo $text;
    showShippingMethods();
}

function saveShippingMethod($shipping_id, $apply)
{
    $database = &unocartFactory::getDBO();
    $shipping = new unocartShippingMethod($database);
    if (!$shipping->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showShippingMethods();
        exit();
    }


    if (!$shipping->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        showShippingMethods();
        exit();
    }
    mosRedirect(($apply) ? ("index2.php?option=com_unocart&act=shippings&task=edit&shipping_id=" .
        $shipping->shipping_id) : ("index2.php?option=com_unocart&act=shippings"));
}

function saveShippingMethodPrice($sh_method_id, $apply)
{
    $database = &unocartFactory::getDBO();
    $shipping_pr = new unocartShippingMethodPrice($database);
    if (!$shipping_pr->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showShippingMethodsPrices();
        exit();
    }

    if (!$shipping_pr->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        showShippingMethodsPrices();
        exit();
    } else {
        $shipping_pr->savePrices($_POST);
        $shipping_pr->saveCountries(mosGetParam($_POST, 'shipping_countries_id'));
    }

    mosRedirect(($apply) ? ("index2.php?option=com_unocart&act=shippings_prices&task=edit&sh_pr_method_id=" .
        $shipping_pr->sh_pr_method_id) : ("index2.php?option=com_unocart&act=shippings_prices"));
}

function deleteShippingMethod($cid)
{
    $database = &unocartFactory::getDBO();
    $query = '';
    $text = '';
    foreach ($cid as $key => $value) {
        $query = "DELETE FROM `#__unocart_shipping_method`
                  WHERE `shipping_id` = '" . $value . "'";
        $database->setQuery($query);
        if ($database->query()) {
            $text .= messageOutput(_UNOCART_SHIPPING_DELETED);

            $query = "SELECT `sh_pr_method_id`
			          FROM `#__unocart_shipping_method_price`
					  WHERE `shipping_method_id` = '" . $value . "'";
            $database->setQuery($query);
            $sh_pr_ids = $database->loadObjectList();

            if (count($sh_pr_ids)) {
                foreach ($sh_pr_ids as $key2 => $value2) {
                    $query = "DELETE FROM `#__unocart_shipping_method_price_weight`
					          WHERE `sh_pr_method_id` = '" . $value2 . "'";
                    $database->setQuery($query);
                    $database->query();
                }
            }

            $query = "DELETE FROM `#__unocart_shipping_method_price`
                   	  WHERE `shipping_method_id` = '" . $value . "'";
            $database->setQuery($query);
            $database->query();

            $query = "DELETE FROM `#__unocart_shipping_method_price_weight`
                   	  WHERE `shipping_method_id` = '" . $value . "'";
            $database->setQuery($query);
            $database->query();
        } else {
            $text .= messageOutput(_UNOCART_ERROR_SHIPPING_DELETED);
        }
    }
    echo $text;
    showShippingMethods();
}

function publishShippingMethod($cid, $flag)
{
    $database = &unocartFactory::getDBO();
    foreach ($cid as $key => $value) {
        $query = "UPDATE `#__unocart_shipping_method`
                   SET `shipping_publish` = '" . $flag . "'
                   WHERE `shipping_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();
    }
    showShippingMethods();
}

function orderShippingMethod($order, $cid, $number)
{
    $database = &unocartFactory::getDBO();
    switch ($order) {
        case 'up':
            $query = "SELECT a.shipping_id, a.shipping_ordering
                   FROM `#__unocart_shipping_method` AS a
                   WHERE a.shipping_ordering < '" . $number . "'
                   ORDER BY a.shipping_ordering DESC
                   LIMIT 1";
            break;
        case 'down':
            $query = "SELECT a.shipping_id, a.shipping_ordering
                   FROM `#__unocart_shipping_method` AS a
                   WHERE a.shipping_ordering > '" . $number . "'
                   ORDER BY a.shipping_ordering ASC
                   LIMIT 1";
    }
    $database->setQuery($query);
    @$database->loadObject($row);
    $query1 = "UPDATE `#__unocart_shipping_method` AS a
                 SET a.shipping_ordering = '" . $row->shipping_ordering . "'
                 WHERE a.shipping_id = '" . $cid . "'";
    $query2 = "UPDATE `#__unocart_shipping_method` AS a
                 SET a.shipping_ordering = '" . $number . "'
                 WHERE a.shipping_id = '" . $row->shipping_id . "'";
    $database->setQuery($query1);
    $database->query();
    $database->setQuery($query2);
    $database->query();
    showShippingMethods();
}


function showTaxes()
{
    $database = &unocartFactory::getDBO();
    $rows = unocartTax::getAllTaxes(0);
    HTML_UNOCART::showTaxes($rows);
}

function editTax($tax_id = null)
{
    $database = &unocartFactory::getDBO();
    $tax = new unocartTax($database);
    $tax->load($tax_id);
    $edit = ($tax_id) ? ($edit = 1) : ($edit = 0);
    HTML_UNOCART::editTax($tax, $edit);
}

function saveTax($tax_id, $apply)
{
    $database = &unocartFactory::getDBO();
    $tax = new unocartTax($database);
    if (!$tax->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showTaxes();
        exit();
    }

    if (!$tax->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        showTaxes();
        exit();
    }
    mosRedirect(($apply) ? ("index2.php?option=com_unocart&act=taxes&task=edit&tax_id=" .
        $tax->tax_id) : ("index2.php?option=com_unocart&act=taxes"));
}

function deleteTax($cid)
{
    $database = &unocartFactory::getDBO();
    $text = '';
    foreach ($cid as $key => $value) {
        $tax = new unocartTax($database);
        $tax->load($value);
        $query2 = "SELECT pr.product_id
                   FROM `#__unocart_products` AS pr
                   WHERE pr.product_tax_id = '" . $value . "'";
        $database->setQuery($query2);
        $res = $database->query();
        if ($database->getNumRows($res)) {
            $text .= messageOutput(sprintf(_UNOCART_TAX_NO_DELETED, $tax->tax_name));
            continue;
        }
        $query = "DELETE
                   FROM `#__unocart_taxes`
                   WHERE `tax_id` = '" . $value . "'; ";
        $database->setQuery($query);
        if ($database->query())
            $text .= messageOutput(sprintf(_UNOCART_TAX_DELETED, $tax->tax_name));
    }
    echo $text;
    showTaxes();
}

function showManufacturers()
{
    $database = &unocartFactory::getDBO();
    $rows = unocartManufacturer::getAllManufacturers();
    HTML_UNOCART::showManufacturers($rows);
}

function editManufacturer($man_id = null)
{
    $database = &unocartFactory::getDBO();
    $manufacturer = new unocartManufacturer($database);
    $manufacturer->load($man_id);
    $edit = ($man_id) ? ($edit = 1) : ($edit = 0);
    HTML_UNOCART::editManufacturer($manufacturer, $edit);
}


function saveManufacturer($man_id, $apply)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $man = new unocartManufacturer($database);

    if (!$man->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showManufacturers();
        exit();
    }
    $man->manufacturer_description = html_entity_decode($man->
        manufacturer_description);

    $i = 0;
    if ($_FILES['manufacturer_logo']['size']) {
        $file_name = $unocartConfig->image_manufs_path . "/" . $_FILES['manufacturer_logo']['name'];
        do {
            if (!file_exists($file_name)) {
                if (move_uploaded_file($_FILES['manufacturer_logo']['tmp_name'], $file_name)) {
                    @unlink($unocartConfig->image_manufs_path . "/" . $old_file = $man->
                        manufacturer_logo);
                    $man->manufacturer_logo = basename($file_name);
                    break;
                } else {
                    echo "error uploading file";
                    die();
                }
            } else {
                $file_name = $unocartConfig->image_manufs_path . "/" . $i++ . "_" . $_FILES['manufacturer_logo']['name'];
            }
        } while (1);
    }

    if (!$man->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        showManufacturers();
        exit();
    }
    mosRedirect(($apply) ? ('index2.php?option=com_unocart&act=manufacturers&task=edit&man_id=' .
        $man->manufacturer_id) : ('index2.php?option=com_unocart&act=manufacturers'));
}

function deleteManufacturer($cid)
{
    $database = &unocartFactory::getDBO();
    $text = '';
    foreach ($cid as $key => $value) {
        $query = "DELETE
                   FROM `#__unocart_manufacturers`
                   WHERE `manufacturer_id` = '" . $value . "'; ";
        $manuf = new unocartManufacturer($database);
        $manuf->load($value);
        $database->setQuery($query);
        if ($database->query())
            $text .= messageOutput(sprintf(_UNOCART_MANUFACTURER_DELETED, $manuf->
                manufacturer_name));
    }
    echo $text;
    showManufacturers();
}

function publishManufacturer($cid, $flag)
{
    $database = &unocartFactory::getDBO();
    foreach ($cid as $key => $value) {
        $query = "UPDATE `#__unocart_manufacturers`
                   SET `manufacturer_publish` = '" . $flag . "'
                   WHERE `manufacturer_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();
    }
    showManufacturers();
}


function showOrderStatus()
{
    $rows = unocartOrderStatus::getAllOrders();
    HTML_UNOCART::showOrderStatus($rows);
}

function deleteOrder($cid)
{
    $database = &unocartFactory::getDBO();
    if (count($cid)) {
        foreach ($cid as $key => $value) {
            $query = "DELETE FROM `#__unocart_orders` WHERE `order_id` = '" . $value . "'";
            $database->setQuery($query);
            if ($database->query()) {
                $query = "DELETE FROM `#__unocart_order_item` WHERE `order_id` = '" . $value .
                    "'";
                $database->setQuery($query);
                $database->query();
                $query = "DELETE FROM `#__unocart_order_history` WHERE `order_id` = '" . $value .
                    "'";
                $database->setQuery($query);
                $database->query();
            }
        }
    }
    mosRedirect('index2.php?option=com_unocart&act=orders');
}

function editOrderStatus($status_id = null)
{
    $database = &unocartFactory::getDBO();
    $order_status = new unocartOrderStatus($database);
    $order_status->load($status_id);
    $edit = ($status_id) ? ($edit = 1) : ($edit = 0);
    HTML_UNOCART::editOrderStatus($order_status, $edit);
}

function saveOrderStatus($status_id, $apply)
{
    $database = &unocartFactory::getDBO();
    $order_status = new unocartOrderStatus($database);
    if (!$order_status->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showOrderStatus();
        exit();
    }

    if (!$order_status->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        showOrderStatus();
        exit();
    }
    mosRedirect(($apply) ? ("index2.php?option=com_unocart&act=order_status&task=edit&status_id=" .
        $order_status->status_id) : ("index2.php?option=com_unocart&act=order_status"));
}

function deleteOrderStatus($cid)
{
    $database = &unocartFactory::getDBO();
    $text = '';
    $query = '';
    foreach ($cid as $key => $value) {
        $query = "DELETE FROM `#__unocart_order_status`
                   WHERE `status_id` = '" . $value . "'; ";
        $database->setQuery($query);
        if ($database->query())
            $text .= messageOutput(_UNOCART_ORDER_STATUS_DELETED);
        else
            $text .= messageOutput(_UNOCART_ORDER_STATUS_ERROR_DELETED);
    }
    echo $text;
    showOrderStatus();
}

function addToProductImage($product_id, $name_image, $name_thumb)
{
    $database = &unocartFactory::getDBO();
    $query = "INSERT INTO `#__unocart_products_images`
   	           SET `product_id` = '" . $product_id . "', `image_thumb` = '" . $name_thumb .
        "', `image_name` = '" . $name_image . "'";
    $database->setQuery($query);
    $database->query();
}


function addToProductVideo($product_id, $name_video, $preview_image = '')
{
    $database = &unocartFactory::getDBO();
    $query = "INSERT INTO `#__unocart_products_videos`
   	           SET `product_id` = '" . $product_id . "', `video_name` = '" . $name_video .
        "', `video_preview` = '" . $preview_image . "'";
    $database->setQuery($query);
    $database->query();
}

function deleteImageFromProduct($image_id)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $query = "SELECT image.image_name, image.image_thumb
               FROM `#__unocart_products_images` AS image
               WHERE image.image_id = '" . $image_id . "'";
    $database->setQuery($query);
    @$database->loadObject($row);
    $query = "DELETE FROM `#__unocart_products_images`
               WHERE `image_id` = '" . $image_id . "'";
    $database->setQuery($query);
    $database->query();
    @unlink($unocartConfig->image_product_path . '/' . $row->image_name);
    @unlink($unocartConfig->image_product_path . '/' . $row->image_thumb);

}

function deleteVideoFromProduct($video_id)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $query = "SELECT video.video_name, video.video_preview
               FROM `#__unocart_products_videos` AS video
               WHERE video.video_id = '" . $video_id . "'";
    $database->setQuery($query);
    @$database->loadObject($row);
    unlink($unocartConfig->video_product_path . '/' . $row->video_name);
    unlink($unocartConfig->video_product_path . '/previews/' . $row->video_preview);

    $query = "DELETE FROM `#__unocart_products_videos`
               WHERE `video_id` = '" . $video_id . "'";
    $database->setQuery($query);
    $database->query();
}


function showProducts($category_id)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $limitstart = mosGetParam($_REQUEST, 'limitstart', 0);
    $limit = mosGetParam($_REQUEST, 'limit', 10);
    $text_search = mosGetParam($_REQUEST, 'text_search');
    $total = unocartProduct::getCountAllProducts($category_id, $text_search);

    require_once (JPATH_BASE . '/administrator/includes/pageNavigation.php');
    $pageNav = new mosPageNav($total, $limitstart, $limit);
    $rows = unocartProduct::getAllProducts($category_id, null, $pageNav->limitstart,
        $pageNav->limit, $text_search);

    $parentTop->category_id = 0;
    $parentTop->category_name = _UNOCART_ALL_PRODUCTS;
    $categories_select = buildTreeCategory(0);
    array_unshift($categories_select, $parentTop);
    $lists['treecategories'] = mosHTML::selectList($categories_select, 'current_cat',
        'class="inputbox" id = "category_ordering" size="1"', 'category_id',
        'category_name', $category_id);

    HTML_UNOCART::showAllProducts($rows, $lists, $category_id, $pageNav, $text_search);
}

function editProduct($product_id)
{
    global $unocartConfig, $shop_type;
    $database = &unocartFactory::getDBO();
    $product = new unocartProduct($database);
    $product->load($product_id);
    $product->getAddPrices(1);
    if (is_array($product->product_add_prices)) {
        $product->product_add_prices = array_reverse($product->product_add_prices);
    }

    if ($product_id) {
        $all_languages = getAllLanguages();
        $query = "SELECT prod_descr.*
                   FROM `#__unocart_products_description` AS prod_descr
                   WHERE prod_descr.product_id = '" . $product_id . "'";
        $database->setQuery($query);
        $rows = $database->loadObjectList();

        // Zaganyau vsi language in masyv
        foreach ($all_languages as $key => $value) {
            $lang[] = $value->language;
        }

        $langs = array();
        foreach ($rows as $key => $value) {
            if (!in_array($value->language, $lang)) {
                unset($rows[$key]);
            } else {
                $langs[] = $value->language;
            }
        }
        unset($lang);
        foreach ($all_languages as $lang) {
            if (!in_array($lang->language, $langs)) {
                $object->language = $lang->language;
                $object->product_id = $rows[0]->product_id;
                $object->product_name = $object->product_description = $object->
                    product_short_description = $object->product_meta_title = $object->
                    product_meta_description = $object->product_meta_keyword = '';
                $rows[] = $object;
                unset($object);
            }
        }
        $edit = 1;
    } else {
        $rows = getAllLanguages();
        $edit = 0;
        $category->products_sorting = 1;
        $category->products_sorting2 = 1;
    }

    $all_products = unocartProduct::getAllProducts(0, $product_id);
    $all_taxes = unocartTax::getAllTaxes();
    if ($edit) {
        $images = $product->getImages();
        $videos = $product->getVideos();
        $categories_select = $product->getCategories();
        $related_pr = $product->getRelatedProducts(0);
    } else {
        $images = array();
        $videos = array();
        $categories_select = null;
        $related_pr = array();
    }
    $list_tax = array();
    $list_tax[] = mosHTML::makeOption('0', _UNOCART_SELECT, 'tax_id', 'tax_name');
    foreach ($all_taxes as $tax) {
        $list_tax[] = mosHTML::makeOption($tax->tax_id, $tax->tax_name . ' {' . $tax->
            tax_value . '%)', 'tax_id', 'tax_name');
    }

    $categories = buildTreeCategory(0);
    $lists['images'] = $images;
    $lists['videos'] = $videos;
    $lists['description'] = $rows;
    $lists['currencies'] = unocartCurrency::getAllCurrencies();


    $pr_sp_type[] = mosHTML::makeOption(0, _UNOCART_SELECT, 'id_pr', 'value_pr');
    foreach ($shop_type as $key => $value) {
        $pr_sp_type[] = mosHTML::makeOption($key, $value, 'id_pr', 'value_pr');
    }
    $lists['product_special_type'] = mosHTML::selectList($pr_sp_type,
        'product_special_type', 'class = "inputbox" size = "1"', 'id_pr', 'value_pr', $product->
        product_special_type);
    $manuf1[0]->manufacturer_id = '0';
    $manuf1[0]->manufacturer_name = _UNOCART_NONE;
    $manufs = unocartManufacturer::getAllManufacturers(0);
    $manufs = array_merge($manuf1, $manufs);

    // Attributes and values

    $lists['attribs'] = $product->getAttributes();
    $all_attributes = unocartAttribut::getAllAttributes();


    $first[] = mosHTML::makeOption('0', _UNOCART_SELECT, 'value_id_to_attr_id',
        'value_name');

    $price_prefix[] = mosHTML::makeOption('=', '=', 'value_prefix_id',
        'prefix_value');
    $price_prefix[] = mosHTML::makeOption('+', '+', 'value_prefix_id',
        'prefix_value');
    $price_prefix[] = mosHTML::makeOption('-', '-', 'value_prefix_id',
        'prefix_value');
    $lists['price_prefix'] = $price_prefix;

    foreach ($all_attributes as $key => $value) {
        $values_for_attribut = unocartValue::getAllValues($value->attr_id);
        if (!count($values_for_attribut)) {
            unset($all_attributes[$key]);
            continue;
        }
        $all_attributes[$key]->values_select = mosHTML::selectList(array_merge($first, $values_for_attribut),
            'value_id[' . $value->attr_id . ']',
            'class = "inputbox" size = "1" id = "value_id_' . $value->attr_id . '"',
            'value_id_to_attr_id', 'value_name');
        $all_attributes[$key]->values = $values_for_attribut;
    }

    $lists['all_attributes'] = $all_attributes;
    // End work with attributes and values

    $lists['manufacturers'] = mosHTML::selectList($manufs, 'product_manufacturer_id',
        'class = "inputbox" size = "1"', 'manufacturer_id', 'manufacturer_name', $product->
        product_manufacturer_id);
    //     $lists['manufacturers'] = mosHTML::selectList($);
    $tax_value = 0;
    foreach ($all_taxes as $tax) {
        if ($tax->tax_id == $product->product_tax_id) {
            $tax_value = $tax->tax_value;
            break;
        }
    }
    $lists['tax'] = mosHTML::selectList($list_tax, 'product_tax_id',
        'class = "inputbox" size = "1" id = "product_tax_id" onchange = "updateNet(); updateGross()"',
        'tax_id', 'tax_name', $product->product_tax_id);
    $lists['categories'] = mosHTML::selectList($categories, 'category_id[]',
        'class="inputbox" size="10" multiple = "multiple" id  = "category_id"',
        'category_id', 'category_name', $categories_select);
    $lists['writeable'] = (is_writable($unocartConfig->image_product_path)) ? ($unocartConfig->
        image_product_path . '::' . messageOutput(_UNOCART_WRITEABLE, 'unocart_green')) : ($unocartConfig->
        image_product_path . '::' . messageOutput(_UNOCART_NON_WRITEABLE));
    $lists['templates'] = getTemplates('product', $product->product_template);
    $lists['related'] = mosHTML::selectList($all_products, 'related_products[]',
        'class = "inpubox" size = "10" multiple = "multiple"', 'product_id',
        'product_name', $related_pr);
    HTML_UNOCART::editProduct($product, $lists, $edit, $tax_value);
}

function saveProduct($apply)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $checkboxes = array("product_is_add_price", "product_publish",
        "product_show_price");
    foreach ($checkboxes as $key => $value) {
        if (!isset($_REQUEST[$value]))
            $_REQUEST[$value] = 0;
    }
    foreach ($_REQUEST as $key => $value)
        $$key = mosGetParam($_POST, $key, "", _MOS_ALLOWRAW);
    $_POST['product_price'] = mosGetParam($_POST, 'product_price_gross');
    // If checkboxes - stavlyu = 0
    if (!isset($related_products))
        $related_products = null;

    $product = new unocartProduct($database);
    if (!$product->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showProducts();
        exit();
    }
    $product->product_publish = $_REQUEST['product_publish'];
    $product->product_date_added = date("Y-m-d H:i:s");


    // When delete all products - unset(set_main_image)
    if (count($_POST['delete_image']) == count($product->getImages())) {
        $product->product_thumb_image = '';
        $product->product_full_image = '';
        unset($set_main_image);
    }

    // Delete image from product
    if (isset($delete_image)) {
        foreach ($delete_image as $key => $value)
            deleteImageFromProduct($key);
    }

//    if (isset($_POST['delete_image'][$set_main_image]))// Почемуто удалено в последней версии
        if ($edit && isset($set_main_image)) {
            $image = new unocartImage($database);
            $image->load($set_main_image);
            if ($image->image_id) {
                $product->product_thumb_image = $image->image_thumb;
                $product->product_full_image = $image->image_name;
            } else {
                $product->setMainImage($product->getImages());
            }
        }

    $i = 0;
    if ($_FILES['product_download_file']['size']) {
        $file_name = $unocartConfig->files_path . $_FILES['product_download_file']['name'];
        do {
            if (!file_exists($file_name)) {
                if (move_uploaded_file($_FILES['product_download_file']['tmp_name'], $file_name)) {
                    $product->product_download_file = basename($file_name);
                    $old_file = $product->getDownloadFile();
                    if (file_exists($unocartConfig->files_path . $old_file))
                        unlink($unocartConfig->files_path . $old_file);
                    break;
                } else {
                    echo "error uploading file";
                    die();
                }
            } else {
                $file_name = $unocartConfig->files_path . $i++ . "_" . $_FILES['product_download_file']['name'];
            }
        } while (1);
    }
    $product->updateAddPrice($product_add_price, $quantity_start, $quantity_finish,
        $product_add_price_delete, $product_is_add_price);
    if (!$product->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        echo $product->_error;
        showProducts();
        exit();
    }

    $product_id = $product->product_id;

    $product->processSpecialType();
    require_once ($unocartConfig->admin_path . 'thumbnail_images.class.php');

    $name_image = $_FILES['product_image']['name'];
    $tmp_image = $_FILES['product_image']['tmp_name'];
    $name_video = $_FILES['product_video']['name'];
    $tmp_video = $_FILES['product_video']['tmp_name'];
    $prev_video = $_FILES['product_video_preview']['name'];
    $prev_tmp = $_FILES['product_video_preview']['tmp_name'];


    // Add video to product
    foreach ($name_video as $key => $value) {
        if (!$value)
            continue;
        $file_video = getFileName($value);
        $path_video = $unocartConfig->video_product_path . "/" . $file_video;
        if (move_uploaded_file($tmp_video[$key], $path_video)) {
            $image_prev_video = '';
            if ($prev_tmp[$key] && $prev_video[$key]) {
                // If exist preview image for this video
                $image_prev_video = getFileName($prev_video[$key]);
                if (!move_uploaded_file($prev_tmp[$key], $unocartConfig->video_product_path .
                    "/preview/" . $image_prev_video))
                    $image_prev_video = '';


            }
            addToProductVideo($product_id, $file_video, $image_prev_video);
        }

    }

    if (isset($delete_video)) {
        foreach ($delete_video as $key => $value) {
            deleteVideoFromProduct($key);
        }
    }
    // Delete video from product
    // 111111111111111111111111111111111

    // Add image to product
    $added = 0;
    $size_full_product = mosGetParam($_REQUEST, 'size_full_product');
    foreach ($name_image as $key => $value) {
        if (!$value)
            continue;
        $name_image = getFileName($value);
        $name_thumb = 'thumb_' . $name_image;

        $path_image = $unocartConfig->image_product_path . "/" . $name_image;
        $path_thumb = $unocartConfig->image_product_path . "/" . $name_thumb;
        if (move_uploaded_file($tmp_image[$key], $path_image)) {
            // Get the image size
            if ($size_im_product == 3) {
                list($product_width_image, $product_height_image, $type, $attr) = getimagesize($path_image);
            }
            $img = new thumbnail_images();
            $img->PathImgOld = $path_image;
            $img->PathImgNew = $path_thumb;
            $img->NewWidth = $product_width_image;
            $img->NewHeight = $product_height_image;
            if (!$img->create_thumbnail_images()) {
                echo _UNOCART_ERROR_CREATING_THUMBNAIL;
                return;
            } else {

                addToProductImage($product_id, $name_image, $name_thumb);

                if ((!$added && !$edit) || (!$product->product_thumb_image && !$product->
                    product_full_image)) {
                    $added = 1;
                    $product = new unocartProduct($database);
                    $product->load($product_id);
                    $product->product_thumb_image = $name_thumb;
                    $product->product_full_image = $name_image;
                    $product->store();
                }
            }
            // if set in admin width and heigth for full images
            if ($size_full_product) {
                $img = new thumbnail_images();
                $img->PathImgOld = $path_image;
                $img->PathImgNew = $path_image . "temp";
                if ($size_full_product == 1) {
                    $img->NewWidth = $unocartConfig->image_product_full_width;
                    $img->NewHeight = $unocartConfig->image_product_full_height;
                } else
                    if ($size_full_product == 2) {
                        $img->NewWidth = mosGetParam($_POST, 'product_full_width_image');
                        $img->NewHeight = mosGetParam($_POST, 'product_full_height_image');
                    }
                if (!$img->create_thumbnail_images()) {
                    echo _UNOCART_ERROR_SAVING_IMAGE;
                    return;
                }
                unlink($img->PathImgOld);
                rename($img->PathImgNew, $img->PathImgOld);
            }
        }
    }


    // Work with attributes
    $query = "DELETE FROM `#__unocart_products_attr`
	               WHERE `product_id` = '" . $product_id . "'";
    $database->setQuery($query);
    $database->query();

    foreach ($attr_value as $key => $value) {
        $query = "INSERT INTO `#__unocart_products_attr`
	     	          SET `product_id` = '" . $product_id . "',
	     	              `attr_value_id` = '" . $key . "',
	     	              `value_price` = '" . $value . "',
	     	              `price_prefix` = '" . $price_prefix[$key] . "'";
        $database->setQuery($query);
        $database->query();
    }

    // End wotk with attributes


    $product->addRelationCategories($category_id);
    // Yakscho product vshe isnuvava, to vyluchaju cinu, raltions and other products a potim insert
    if ($edit) {
        $query = "DELETE FROM `#__unocart_products_relations`
                  WHERE `product_id` = '" . $product_id . "'";
        $database->setQuery($query);
        $database->query();
    }

    if (count($related_products))
        foreach ($related_products as $key => $value) {
            $query = "INSERT INTO `#__unocart_products_relations`
                  SET `product_id` = '" . $product_id .
                "', `product_related_id` = '" . $value . "'";
            $database->setQuery($query);
            $database->query();
        }

    foreach ($product_name as $key => $value) {
        $query = "REPLACE INTO `#__unocart_products_description`
    	          SET `product_id` = '" . $product_id . "', `language` = '" . $key .
            "', `product_name` = '" . replaceToNbsp($product_name[$key]) .
            "', `product_description` = '" . html_entity_decode($product_description[$key]) .
            "', `product_short_description` = '" . html_entity_decode($product_short_description[$key]) .
            "', `product_meta_title` = '" . $product_meta_title[$key] .
            "', `product_meta_description` = '" . $product_meta_description[$key] .
            "', `product_meta_keyword` = '" . $product_meta_keyword[$key] . "'";
        $database->setQuery($query);
        $database->query();
    }
    mosRedirect(($apply) ? ("index2.php?option=com_unocart&act=products&task=edit&current_cat=" .
        $current_cat . "&product_id=" . $product->product_id) : ("index2.php?option=com_unocart&act=products&current_cat=" .
        $current_cat));
}

function publishProduct($cid, $flag)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $query = '';
    foreach ($cid as $key => $value) {
        $query = "UPDATE `#__unocart_products`
                   SET `product_publish` = '" . $flag . "'
                   WHERE `product_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();
    }
}

function copyProduct($cid)
{
    $database = &unocartFactory::getDBO();

    // Get all data about products
    $tables = array('attr', 'description', 'images', 'prices', 'relations',
        'reviews', 'sp_type_info', 'to_categories', 'videos');
    foreach ($cid as $key => $value) {
        $product = new unocartProduct($database);
        $product->load($value);
        $product->product_id = null;
        $product->store();

        $array = array();
        foreach ($tables as $table) {
            $query = "SELECT *
			          FROM `#__unocart_products_" . $table . "` AS prod_table
					  WHERE prod_table.product_id = '" . $value . "'";
            $database->setQuery($query);
            $array[] = $database->loadAssocList();
        }

        $i = 0;
        foreach ($array as $key2 => $value2) {
            if (count($value2)) {
                foreach ($value2 as $key3 => $value3) {
                    $database->setQuery(buildQuery($tables[$i], $value3, $product->product_id));
                    $database->query();
                }
            }
            $i++;
        }
    }
}

function buildQuery($table, $array, $product_id)
{
    $query = "INSERT INTO `#__unocart_products_" . $table . "` SET ";
    $array_keys = array('image_id', 'price_id', 'review_id', 'video_id',
        'product_attr_id', 'value_id');
    foreach ($array as $key => $value) {
        if (in_array($key, $array_keys))
            continue;
        if ($key == 'product_id')
            $value = $product_id;
        $query .= "`" . $key . "` = '" . $value . "', ";
    }
    return $query = Jstring::substr($query, 0, Jstring::strlen($query) - 2);
}


function orderProduct($order, $product_id, $number, $category_id)
{
    $database = &unocartFactory::getDBO();
    switch ($order) {
        case 'up':
            $query = "SELECT a.*
                   FROM `#__unocart_products_to_categories` AS a
                   WHERE a.product_ordering < '" . $number .
                "' AND a.category_id = '" . $category_id . "'
                   ORDER BY a.product_ordering DESC
                   LIMIT 1";
            break;
        case 'down':
            $query = "SELECT a.*
                   FROM `#__unocart_products_to_categories` AS a
                   WHERE a.product_ordering > '" . $number .
                "' AND a.category_id = '" . $category_id . "'
                   ORDER BY a.product_ordering ASC
                   LIMIT 1";
    }

    $database->setQuery($query);
    @$database->loadObject($row);

    $query1 = "UPDATE `#__unocart_products_to_categories` AS a
                 SET a.product_ordering = '" . $row->product_ordering . "'
                 WHERE a.product_id = '" . $product_id .
        "' AND a.category_id = '" . $category_id . "'";
    $query2 = "UPDATE `#__unocart_products_to_categories` AS a
                 SET a.product_ordering = '" . $number . "'
                 WHERE a.product_id = '" . $row->product_id .
        "' AND a.category_id = '" . $category_id . "'";
    $database->setQuery($query1);
    $database->query();
    $database->setQuery($query2);
    $database->query();
}


function deleteProduct($cid)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $text = '';

    foreach ($cid as $key => $value) {
        $product = new unocartProduct($database);
        $product->load($value);
        $query = "DELETE FROM `#__unocart_products`
                   WHERE `product_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();

        $query = "DELETE FROM `#__unocart_products_description`
                   WHERE `product_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();

        $query = "DELETE FROM `#__unocart_products_attr`
                  WHERE `product_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();

        /* Old non used
        $query = "DELETE FROM `#__unocart_products_price`
        WHERE `product_id` = '" . $value . "'; ";
        */
        $query = "DELETE FROM `#__unocart_products_relations`
                   WHERE `product_id` = '" . $value .
            "' OR `product_related_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();

        $query = "DELETE FROM `#__unocart_products_to_categories`
                   WHERE `product_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();

        $images = $product->getImages();
        $videos = $product->getVideos();

        if ($product->product_thumb_image) {
            unlink($unocartConfig->image_product_path . "/" . $product->product_thumb_image);
        }

        if ($product->product_full_image) {
            unlink($unocartConfig->image_product_path . "/" . $product->product_full_image);
        }

        if ($product->product_download_file) {
            unlink($unocartConfig->files_path . $product->product_download_file);
        }


        if (count($images)) {
            foreach ($images as $image) {
                @unlink($unocartConfig->image_product_path . "/" . $image->image_thumb);
                @unlink($unocartConfig->image_product_path . "/" . $image->image_name);
            }
        }

        if (count($videos)) {
            foreach ($videos as $video) {
                unlink($unocartConfig->image_product_path . "/" . $video->video_name);
            }
        }
        $text .= messageOutput(sprintf(_UNOCART_PRODUCT_DELETED, getNameProductById($value)));
    }
    echo $text;
}

function showAttributes()
{
    $rows = unocartAttribut::getAllAttributes();
    foreach ($rows as $key => $value) {
        $rows[$key]->values = splitValuesArrayObject(unocartValue::getAllValues($rows[$key]->
            attr_id), 'value_name');
    }
    HTML_UNOCART::showAttributes($rows);
}

function editAttribute($attr_id)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();

    if ($attr_id) {
        $all_languages = getAllLanguages();
        $query = "SELECT attr.*
                  FROM `#__unocart_attr` AS attr
                  WHERE attr.attr_id = '" . $attr_id . "'";
        $database->setQuery($query);
        $rows = $database->loadObjectList();

        // Zaganyau vsi language in masyv
        foreach ($all_languages as $key => $value) {
            $lang[] = $value->language;
        }

        $langs = array();
        foreach ($rows as $key => $value) {
            if (!in_array($value->language, $lang)) {
                unset($rows[$key]);
            } else {
                $langs[] = $value->language;
            }
        }
        unset($lang);
        foreach ($all_languages as $lang) {
            if (!in_array($lang->language, $langs)) {
                $obj->attr_id = $rows[0]->attr_id;
                $obj->attr_name = '';
                $obj->attr_type = $rows[0]->attr_type;
                $obj->language = $lang->language;
                $rows[] = $obj;
                unset($obj);
            }
        }
        $attr_type = $rows[0]->attr_type;
        $edit = 1;
    } else {
        $rows = getAllLanguages();
        $edit = 0;
        $attr_type = 1;
    }

    $types[] = mosHTML::makeOption('1', '1. Select', 'attr_type_id', 'attr_type');
    $types[] = mosHTML::makeOption('2', '2. Radio', 'attr_type_id', 'attr_type');
    $lists['type_attribut'] = mosHTML::selectList($types, 'attr_type',
        'class = "inputbox" size = "1"', 'attr_type_id', 'attr_type', $attr_type);
    HTML_UNOCART::editAttribute($rows, $attr_id, $lists, $edit);
}

function saveAttribute($attr_id, $attr_type, $attribs, $apply)
{
    $database = &unocartFactory::getDBO();
    if (!$attr_id) {
        $query = "SELECT MAX(attr_id) AS attr_id, MAX(attr_ordering) AS attr_ordering
      	          FROM `#__unocart_attr`";
        $database->setQuery($query);
        @$database->loadObject($row);
        $attr_id = $row->attr_id + 1;
        $attr_ordering = $row->attr_ordering + 1;

        foreach ($attribs as $key => $value) {
            $query = "INSERT INTO `#__unocart_attr`
	                 SET `attr_id` = '" . $attr_id . "', `attr_name` = '" . $value .
                "', `language` = '" . $key . "', `attr_ordering` = '" . $attr_ordering .
                "', `attr_type` = '" . $attr_type . "'";
            $database->setQuery($query);
            $database->query();
        }
    } else {
        foreach ($attribs as $key => $value) {
            // Vyznachaju, chy e zapys z takoju movoju v table, yakscho e - to update, yakscon ni - to insert
            $query = "SELECT attr.attr_id, attr.attr_ordering
		              FROM `#__unocart_attr` AS attr
		              WHERE attr.attr_id = '" . $attr_id . "' AND attr.language = '" .
                $key . "'";
            $database->setQuery($query);
            $database->loadObject($row);
            if (is_object($row)) {
                $query = "UPDATE `#__unocart_attr`
			   	          SET attr_name = '" . $value . "', `attr_ordering` = '" . $row->
                    attr_ordering . "', `attr_type` = '" . $attr_type . "'
			   	          WHERE attr_id = '" . $attr_id . "' AND language = '" . $key .
                    "'";
            } else {
                $query = "INSERT INTO `#__unocart_attr`
			   	          SET attr_name = '" . $value . "', attr_id = '" . $attr_id .
                    "', language = '" . $key . "', `attr_type` = '" . $attr_type . "'";
            }
            $database->setQuery($query);
            $database->query();
            unset($row);
        }
    }
    mosRedirect(($apply) ? ("index2.php?option=com_unocart&act=attributes&task=edit&attr_id=" .
        $attr_id) : ("index2.php?option=com_unocart&act=attributes"));
}


function deleteAttribute($cid)
{
    $database = &unocartFactory::getDBO();
    $text = '';
    foreach ($cid as $key => $value) {
        $query = "DELETE
                   FROM `#__unocart_attr`
                   WHERE `attr_id` = '" . $value . "'; ";
        $database->setQuery($query);
        if ($database->query())
            $text .= messageOutput(_UNOCART_ATTRIBUT_DELETED);
    }
    echo $text;
    showAttributes();
}

function orderAttribute($order, $cid, $number)
{
    $database = &unocartFactory::getDBO();
    switch ($order) {
        case 'up':
            $query = "SELECT a.attr_id, a.attr_ordering
                   FROM `#__unocart_attr` AS a
                   WHERE a.attr_ordering < '" . $number . "'
                   ORDER BY a.attr_ordering DESC
                   LIMIT 1";
            break;
        case 'down':
            $query = "SELECT a.attr_id, a.attr_ordering
                   FROM `#__unocart_attr` AS a
                   WHERE a.attr_ordering > '" . $number . "'
                   ORDER BY a.attr_ordering ASC
                   LIMIT 1";
    }
    $database->setQuery($query);
    @$database->loadObject($row);
    $query1 = "UPDATE `#__unocart_attr` AS a
                 SET a.attr_ordering = '" . $row->attr_ordering . "'
                 WHERE a.attr_id = '" . $cid . "'";
    $query2 = "UPDATE `#__unocart_attr` AS a
                 SET a.attr_ordering = '" . $number . "'
                 WHERE a.attr_id = '" . $row->attr_id . "'";
    $database->setQuery($query1);
    $database->query();
    $database->setQuery($query2);
    $database->query();
    showAttributes();
}

/* --------------------------------------------------- */

function showValues($attr_id)
{
    $database = &unocartFactory::getDBO();
    $rows = unocartValue::getAllValues($attr_id);
    $attribut = new unocartAttribut($database);
    HTML_UNOCART::showValues($rows, $attr_id, $attribut->getName($attr_id));
}

function editValue($value_id, $attr_id, $op)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    // Delete image for value
    if ($op) {
        $query = "SELECT DISTINCT valu.image
      	          FROM `#__unocart_attr_values` AS valu
      	          WHERE valu.value_id = '" . $value_id . "'";
        $database->setQuery($query);
        $image = $database->loadResult();
        if (unlink(JPATH_BASE . "/administrator/components/com_unocart/images/attr/" . $image)) {
            $query = "UPDATE `#__unocart_attr_values` AS valu
        	          SET valu.image = ''
        	          WHERE valu.value_id = '" . $value_id . "'";
            $database->setQuery($query);
            $database->query();
        }
    }
    // End delete image


    if ($attr_id) {
        $all_languages = getAllLanguages();
        $query = "SELECT attr.*
                  FROM `#__unocart_attr` AS attr
                  WHERE attr.attr_id = '" . $attr_id . "'";
        $database->setQuery($query);
        $rows = $database->loadObjectList();

        // Zaganyau vsi language in masyv
        foreach ($all_languages as $key => $value) {
            $lang[] = $value->language;
        }

        $langs = array();
        foreach ($rows as $key => $value) {
            if (!in_array($value->language, $lang)) {
                unset($rows[$key]);
            } else {
                $langs[] = $value->language;
            }
        }
        unset($lang);
        foreach ($all_languages as $lang) {
            if (!in_array($lang->language, $langs)) {
                $obj->attr_id = $rows[0]->attr_id;
                $obj->attr_name = '';
                $obj->attr_type = $rows[0]->attr_type;
                $obj->language = $lang->language;
                $rows[] = $obj;
                unset($obj);
            }
        }
        $attr_type = $rows[0]->attr_type;
        $edit = 1;
    } else {
        $rows = getAllLanguages();

        $edit = 0;
        $attr_type = 1;
    }


    if ($value_id) {
        $all_languages = getAllLanguages();

        $query = "SELECT valu.*
                  FROM `#__unocart_attr_values` AS valu
                  WHERE valu.value_id = '" . $value_id .
            "' OR valu.value_name IS NULL";
        $database->setQuery($query);
        $rows = $database->loadObjectList();


        // Zaganyau vsi language in masyv
        $lang = array();
        foreach ($all_languages as $key => $value) {
            $lang[] = $value->language;
        }

        $desc_lang = array();
        foreach ($rows as $key => $value) {
            if (!in_array($value->language, $lang)) {
                unset($rows[$key]);
            } else {
                $desc_lang[] = $value->language;
            }
        }

        foreach ($all_languages as $lang) {
            if (!in_array($lang->language, $desc_lang)) {
                $obj->value_id = $rows[0]->value_id;
                $obj->value_name = '';
                $obj->language = $lang->language;
                $rows[] = $obj;
                unset($obj);
            }
        }
    } else {
        $edit = 0;
        $rows = getAllLanguages();
    }
    HTML_UNOCART::editValue($rows, $value_id, $attr_id, $edit);
}

function saveValue($value_id, $attr_id, $values, $apply)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $image = '';
    if (isset($_FILES['image'])) {
        $name_file = getFileName($_FILES['image']['name']);
        $path_image = $unocartConfig->admin_path . "/images/attr/" . $name_file;
        if ($_FILES['image']['name']) {
            if (move_uploaded_file($_FILES['image']['tmp_name'], $path_image)) {
                $image = $name_file;
            } else {
                echo "eror upload file";
                return;
            }
        }
    }

    if (!$value_id) {
        $query = "SELECT MAX(value_id) AS value_id, MAX(value_ordering) + 1 AS value_ordering
      	          FROM `#__unocart_attr_values`";
        $database->setQuery($query);
        @$database->loadObject($row);
        $value_id = ++$row->value_id;
        $value_ordering = $row->value_ordering;
        foreach ($values as $key => $value) {
            $query = "INSERT INTO `#__unocart_attr_values`
		               SET `value_id` = '" . $value_id . "',
		                   `value_name` = '" . $value . "',
		                   `language` = '" . $key . "',
		                   `value_ordering` = '" . $value_ordering . "',
		                   `image` = '" . $image . "'";
            $database->setQuery($query);
            $database->query();
        }
        $query = "INSERT INTO `#__unocart_attr_to_values`
	              SET `attr_id` = '" . $attr_id . "',
	                  `value_id` = '" . $value_id . "'";
        $database->setQuery($query);
        $database->query();
    } else {
        if ($image) {
            // Vytyaguju staryj image i vyluchaju jogo
            $query = "SELECT DISTINCT valu.image
		            FROM `#__unocart_attr_values` AS valu
		            WHERE valu.value_id = '" . $value_id . "'";
            $database->setQuery($query);
            $old_image = $database->loadResult();
            if (file_exists($unocartConfig->admin_path . "/images/attr/" . $old_image))
                unlink($unocartConfig->admin_path . "/images/attr/" . $old_image);
        }

        foreach ($values as $key => $value) {
            // Vyznachaju, chy e zapys z takoju movoju v table, yakscho e - to update, yakscon ni - to insert
            $query = "SELECT valu.value_id
		              FROM `#__unocart_attr_values` AS valu
		              WHERE valu.value_id = '" . $value_id . "' AND valu.language = '" .
                $key . "'";
            $database->setQuery($query);
            $res = $database->query();
            if ($database->getNumRows($res)) {
                $query = "UPDATE `#__unocart_attr_values`
			   	          SET value_name = '" . $value . "', `image` = '" . $image . "'
			   	          WHERE value_id = '" . $value_id . "' AND language = '" . $key .
                    "'";
            } else {
                $query = "INSERT INTO `#__unocart_attr_values`
			   	          SET value_name = '" . $value . "', value_id = '" . $value_id .
                    "', language = '" . $key . "', `image` = '" . $image . "'";
            }
            $database->setQuery($query);
            $database->query();
        }
    }
    mosRedirect(($apply) ? ("index2.php?option=com_unocart&act=values&task=edit&attr_id=" .
        $attr_id . "&value_id=" . $value_id) : ("index2.php?option=com_unocart&act=values&attr_id=" .
        $attr_id));
}


function deleteValue($cid)
{
    $database = &unocartFactory::getDBO();
    $text = '';
    foreach ($cid as $key => $value) {

        $query = "DELETE
                   FROM `#__unocart_attr_to_values`
                   WHERE `value_id` = '" . $value . "'";
        $database->setQuery($query);
        $database->query();

        $query = "DELETE
                   FROM `#__unocart_attr_values`
                   WHERE `value_id` = '" . $value . "'";
        $database->setQuery($query);
        if ($database->query())
            $text .= messageOutput(_UNOCART_ATTRIBUT_DELETED);
    }
    echo $text;
}


function orderValue($order, $cid, $number, $attr_id)
{
    $database = &unocartFactory::getDBO();
    switch ($order) {
        case 'up':
            $query = "SELECT a.value_id, a.value_ordering
                   FROM `#__unocart_attr_values` AS a
                   INNER JOIN `#__unocart_attr_to_values` AS attr_to_val ON attr_to_val.value_id = a.value_id
                   WHERE a.value_ordering < '" . $number .
                "' AND attr_to_val.attr_id = '" . $attr_id . "'
                   ORDER BY a.value_ordering DESC
                   LIMIT 1";
            break;
        case 'down':
            $query = "SELECT a.value_id, a.value_ordering
                   FROM `#__unocart_attr_values` AS a
                   INNER JOIN `#__unocart_attr_to_values` AS attr_to_val ON attr_to_val.value_id = a.value_id
                   WHERE a.value_ordering > '" . $number .
                "' AND attr_to_val.attr_id = '" . $attr_id . "'
                   ORDER BY a.value_ordering ASC
                   LIMIT 1";
    }
    $database->setQuery($query);
    @$database->loadObject($row);
    $query1 = "UPDATE `#__unocart_attr_values` AS a, `#__unocart_attr_to_values` AS attr_to_val
                 SET a.value_ordering = '" . $row->value_ordering . "'
                 WHERE a.value_id = '" . $cid .
        "' AND attr_to_val.value_id = a.value_id AND attr_to_val.attr_id = '" . $attr_id .
        "'";
    $query2 = "UPDATE `#__unocart_attr_values` AS a, `#__unocart_attr_to_values` AS attr_to_val
                 SET a.value_ordering = '" . $number . "'
                 WHERE a.value_id = '" . $row->value_id .
        "' AND attr_to_val.value_id = a.value_id AND attr_to_val.attr_id = '" . $attr_id .
        "'";
    $database->setQuery($query1);
    $res = $database->query();
    $database->setQuery($query2);
    $database->query();
    showValues($attr_id);
}


/* ----------------------------------------------*/


function showOrders()
{
    $status_id = mosGetParam($_REQUEST, 'status_id', 0);
    $limitstart = mosGetParam($_REQUEST, 'limitstart', 0);
    $limit = mosGetParam($_REQUEST, 'limit', 10);
    $total = unocartOrder::getCountAllOrders($status_id);
    require_once (JPATH_BASE . '/administrator/includes/pageNavigation.php');
    $pageNav = new mosPageNav($total, $limitstart, $limit);
    $rows = unocartOrder::getAllOrders($pageNav->limitstart, $pageNav->limit, $status_id);
    $lists['status_orders'] = unocartOrderStatus::getAllOrders();
    HTML_UNOCART::showOrders($rows, $lists, $pageNav);
}

function updateStatus($order_id, $order_status, $status_id, $notify, $comments,
    $include, $view_order)
{
    global $unocartConfig, $database;
    $order = new unocartOrder($database);
    $order->load($order_id);
    $order->order_status = $order_status;
    $order->order_m_date = mktime();
    $order->store();

    $order_history = new unocartOrderHistory($database);
    $order_history->order_id = $order_id;
    $order_history->order_status_id = $order_status;
    $order_history->status_date_added = date("Y-m-d H:i:s");
    $order_history->customer_notify = $notify;
    $order_history->comments = $comments;

    $order_history->store();


    if ($notify) {
        $user = new unocartUser($database);
        $user->load($order->user_id);
        $new_status = new unocartOrderStatus($database);
        $new_status->load($order_status);
        $comments = ($include) ? ($comments) : ('');
        mosMail($unocartConfig->contact_email, $unocartConfig->store_name, $user->email,
            sprintf(_UNOCART_ORDER_STATUS_CHANGE_SUBJECT, $order_id), sprintf(_UNOCART_ORDER_STATUS_CHANGE_MESSAGE,
            $user->f_name, $user->l_name, $order->order_id, $new_status->status_name, $comments),
            0);
    }
    echo messageOutput(_UNOCART_ORDER_STATUS_CHANGED);
    if ($view_order)
        showOrder($order_id);
    else
        showOrders();
}

function showOrder($order_id)
{
    $database = &unocartFactory::getDBO();
    $order = new unocartOrder($database);
    $order->load($order_id);
    $shipping_method = new unocartShippingMethod($database);
    $shipping_method->load($order->shipping_method_id);
    $order->shipping_info = $shipping_method->shipping_name;
    $order_items = $order->getAllItems();
    $order_history = $order->getHistory();
    $lists['status'] = mosHTML::selectList(unocartOrderStatus::getAllOrders(),
        'order_status', 'class = "inputbox" size = "1" id = "order_status"', 'status_id',
        'status_name', $order_history[count($order_history) - 1]->status_id);
    HTML_UNOCART::showOrder($order, $order_history, $order_items, $lists, 0);
}

function printOrder($order_id)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $order = new unocartOrder($database);
    $order->load($order_id);
    $shipping_method = new unocartShippingMethod($database);
    $shipping_method->load($order->shipping_method_id);
    $order->shipping_info = $shipping_method->shipping_name;
    $order->getStatus();
    $order->products = $order->getAllItems();
    $order->calcNettoPriceObject();

    $order->netto_sum = $order->calcSumNetto();
    /*
    Ranishe bulo tak, Klaus zahotiv po-inshomu
    HTML_UNOCART::showOrder($order, null, $order_items, null, 1);
    */
    /* Klaus zahotiv tak
    Zrobyv novyi template for print order 
    */
    $smarty = smarty_init();
    $smarty->assign('order', $order);
    $smarty->assign('config', $unocartConfig);
    $smarty->display('print_order.tpl');
    // ---------------------------------

}


function showShopUsers()
{
    $limitstart = mosGetParam($_REQUEST, 'limitstart', 0);
    $limit = mosGetParam($_REQUEST, 'limit', 10);
    $total = unocartUser::getCountAllUsers();
    require_once (JPATH_BASE . '/administrator/includes/pageNavigation.php');
    $pageNav = new mosPageNav($total, $limitstart, $limit);
    $rows = unocartUser::getAllUsers($pageNav->limitstart, $pageNav->limit);
    HTML_UNOCART::showUsers($rows, $pageNav);
}

function editShopUser($user_id)
{
    global $acl, $mainframe, $my, $unocartConfig;
    $database = &unocartFactory::getDBO();
    $user = new unocartUser($database);
    $user->load($user_id);
    $_POST['cid'][0] = $_REQUEST['cid'][0] = $user->user_id; // Cheat Joomla!
    $_REQUEST['task'] = $task = 'edit';
    $option = 'com_users'; // Cheat Joomla 1.5
    $mainframe->_path->admin_html = JPATH_BASE .
        '/administrator/components/com_users/admin.users.html.php';
    $mainframe->_path->class = JPATH_BASE .
        '/administrator/components/com_users/users.class.php';

    require_once ($mainframe->_path->admin_html);
    ob_start();
    require_once (JPATH_BASE . '/administrator/components/com_users/admin.users.php');
    $userform = ob_get_contents();
    $userform = Jstring::str_ireplace('<form action="index2.php" method="post" name="adminForm">',
        '', $userform);
    $userform = Jstring::str_ireplace('</form>', '', $userform);
    $userform = Jstring::str_ireplace('<input type="hidden" name="option" value="com_users" />',
        '', $userform);
    $userform = Jstring::str_ireplace('<input type="hidden" name="task" value="" />', '', $userform);
    ob_end_clean();
    $lists['userform'] = $userform;
    $countries = unocartCountry::getAllCountries();
    $lists['country'] = mosHTML::selectList($countries, 'country',
        'class = "inputbox" size = "1"', 'country_id', 'country_name', $user->country);

    $usergroups = unocartUsergroup::getAllUsergroups();
    $lists['usergroups'] = mosHTML::selectList($usergroups, 'usergroup_id',
        'class = "inputbox" size = "1"', 'usergroup_id', 'usergroup_name', $user->
        usergroup_id);

    $mainframe->_path->admin_html = JPATH_BASE .
        '/administrator/components/com_unocart/admin.unocart.html.php';
    $mainframe->_path->class = JPATH_BASE .
        '/administrator/components/com_unocart/unocart.class.php';
    $_REQUEST['option'] = $option = 'com_unocart';
    HTML_UNOCART::editUser($user, $lists);
}

function removeShopUser($cid)
{

}

function saveShopUser($user_id)
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $user_shop = new unocartUser($database);
    $user_shop->load($user_id);
    $user_shop->bind($_POST);

    $user = new mosUser($database);
    $user->load($user_id);
    $user->bind($_POST);

    if (!$user_shop->check(1)) {
        echo "<script> alert('" . html_entity_decode($user_shop->getError(), ENT_QUOTES,
            $unocartConfig->charset) . "'); window.history.go(-1); </script>\n";
        exit();
    }

    if (!$user->check()) {
        echo "<script> alert('" . html_entity_decode($user->getError(), ENT_QUOTES, $unocartConfig->
            charset) . "'); window.history.go(-1); </script>\n";
        exit();
    }

    if (!$user->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        exit;
    }

    if (!$user_shop->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        exit;
    }
    mosRedirect('index2.php?option=com_unocart&act=users');
}

function showUsergroups()
{
    HTML_UNOCART::showAllUsergroups(unocartUsergroup::getAllUsergroups());
}

function editUsergroup($usergroup_id)
{
    $database = &unocartFactory::getDBO();
    $usergroup = new unocartUserGroup($database);
    $usergroup->load($usergroup_id);
    HTML_UNOCART::editUsergroup($usergroup);
}

function saveUsergroup($usergroup_id, $apply)
{
    $database = &unocartFactory::getDBO();
    $usergroup = new unocartUserGroup($database);

    if (!$usergroup->bind($_POST)) {
        echo messageOutput(_UNOCART_ERROR_BIND);
        showUsergroups();
        exit();
    }
    if ($usergroup->usergroup_is_default) {
        $default_usergroup_id = unocartUsergroup::resetDefaultUsergroup();
    }
    $usergroup->usergroup_description = html_entity_decode($usergroup->
        usergroup_description);
    if (!$usergroup->store()) {
        echo messageOutput(_UNOCART_ERROR_SAVE_DATABASE);
        unocartUserGroup::setDefaultUsergroup($default_usergroup_id);
        showUsergroups();
        exit();
    }
    mosRedirect(($apply) ? ('index2.php?option=com_unocart&act=usergroups&task=edit&usergroup_id=' .
        $usergroup->usergroup_id) : ('index2.php?option=com_unocart&act=usergroups'));
}

function deleteUsergroup($usergroup_id)
{
    $database = &unocartFactory::getDBO();
    foreach ($cid as $key => $value) {
        $query = "SELECT `usergroup_name`
		          FROM `#__usergroups`
		          WHERE `usergroup_id` = '" . $value . "'";
        $database->setQuery();
        $usergroup_name = $database->loadResult();
        if (!$database->getAffectedRows()) {
            $query = "DELETE FROM
			          WHERE `usergroup_id` = '" . $value . "'";
            $database->setQuery($query);
            if ($database->query()) {
                $text .= sprintf(_UNOCART_USERGROUP_DELETED, $usergroup_name);
            }
        } else {
            $text .= sprintf(_UNOCART_USERGROUP_NOT_DELETED, $usergroup_name);
        }
    }
    echo $text;
    showUsergroups();
}


function sendReport()
{
    global $my;
    $database = &unocartFactory::getDBO();
    $query = "SELECT `email`
	          FROM `#__users`
			  WHERE `id` = '" . $my->id . "'";
    $database->setQuery($query);
    $email = $database->loadResult();
    $name = mosGetParam($_POST, 'name');
    $phone = mosGetParam($_POST, 'phone');
    $text = mosGetParam($_POST, 'text');
    $message = _UNOCART_REPORT_PHONE . $phone . "\n" . _UNOCART_REPORT_TEXT_INFO . $text;
    if (mosMail($email, $name, "vladzimirs@gmail.com", "UnoCart", $message))
        echo _UNOCART_REPORT_TEXT_THANK;
}

?>